Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rendering a promise return value with React.useEffect

I’m trying to render the value returned from a promise that calls two external APIs into the JSX.

It seems to work the first time, but then I get undefined.

Am I using useEffect the wrong way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default function Dashboard(props) {

    const [pageInfo, setPageInfo] = React.useState();

    async function getPageInfo(props) {

        try {
            const userId = localStorage.getItem('userId');
            let res = await axios.get('http://localhost:8000/user/'+userId);
            let lastPageId = res.data.pages[res.data.pages.length - 1];
            let pageInfoObj = await axios.get('http://localhost:8000/page/'+lastPageId);
            return pageInfoObj.data;
        } catch (err) {
            console.log(err);
        }
    };

    React.useEffect(() => {
        getPageInfo(props)
            .then(data => {
                setPageInfo(data);
            })
    }, [props]);

    return(
      <Typography>
         {pageInfo.pageTitle}
      </Typography>        
    );
}

>Solution :

use optional chaining or initialize your data as per the response structure and put conditionals

  • If response is an array, initialize with an empty array (so you can map over and get no error’s) and also you can check it’s length before rendering like data.length > 0 && data.map()

  • If response is an object, initialize with null so you can check as data && data.blah

  • If it’s a string then may be an empty string 😛

depends on response structure and it’s not mandatory to have exactly same

why ? because, by the first render still the data i.e., pageInfo is not available yet and it will be undefined as it is not initialized with any value so by default is undefined

return(
      <Typography>
         {pageInfo?.pageTitle}
      </Typography>        
    );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading