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>
);
}
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 ie, 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>
);
Looks like there is a backend fetch error in the second time and also initialise your state.
In your code, when there is an error in the fetch call, it simply returns undefined; So, handle the error in the .catch
chain.
export default function Dashboard(props) {
const [pageInfo, setPageInfo] = React.useState({});
async function getPageInfo(props) {
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;
};
React.useEffect(() => {
getPageInfo(props)
.then(data => {
setPageInfo(data);
}).catch(err => {
console.log("Some Error: " + err.message)
})
}, [props]);
return (
<Typography>
{pageInfo.pageTitle}
</Typography>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.