useEffect(() => {
resetState();
if (page === 'ADMISSION') {
fetchAdmissionKitPosts();
} else if (page === 'WEEKLY') {
fetchWeeklyKitPosts();
} else if (page === 'FESTIVAL') {
fetchFestivalKitPosts();
}
}, [page]);
So I want to make different API calls based on the page variable. I have to reset the state before making those calls. But while making the call I'm getting the previous state. I came to know that the setState in react is async in nature, so I assume that that's why I'm getting the previous state in the API call functions.
So my question is, how can I make it so that these API calls only run after the state has been reset?
I know that I can use a callback function in the class-based component with the setState function. But I want to keep this component functional.
You can implement setState callback in functional component with useEffect. if i'm getting it right, you are using two state variables page and posts, if this is the case you should use two useEffect methods like this:
useEffect(() => {
if(page !== ''){
setMarketingPosts([])
}
}, [page]);
useEffect(() => {
if (page === 'ADMISSION') {
fetchAdmissionKitPosts();
} else if (page === 'WEEKLY') {
fetchWeeklyKitPosts();
} else if (page === 'FESTIVAL') {
fetchFestivalKitPosts();
}
setNextPageToken('')
}, [post]);