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?

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>        
    );

Leave a Reply