I cant get the state to be updated when useEffect is called. Currently trying to retrieve posts from my backend server running locally. I am able to get the array when console logging data but after calling setPosts(data), all I get is an empty array when console logging Posts. Tried running retrievePosts with a button and it works fine but I'm trying to get the posts for rendering whenever the page is refreshed.
function App() {
const [posts, setPosts] = useState([]);
async function retrievePosts() {
const {data} = await Axios.get("http://localhost:5000");
console.log(data)
setPosts(data);
console.log(posts);
}
useEffect(()=> {
retrievePosts();
},[]);
return (
<Router>
<Navibar/>
<Routes>
<Route exact path = "/" element = {<Home retrievePosts = {retrievePosts}/>}/>
<Route exact path = "/compose" element = {<Compose/>}/>
</Routes>
</Router>
); }
export default App;
CodePudding user response:
You get this problem because useState
works asynchronous. When you invoke console.log(posts)
after setPosts(data)
your posts
in state is not actually contain data
.
To work with it you should, for example, and another useEffect
and pass to it as dependency posts
and log to console there:
useEffect(() => {
console.log(posts); // you can do anything what you want here when you've got posts
}, [posts])
CodePudding user response:
setPosts() doesn’t update the state immediately instead schedules the state update. I think state should get updated correctly but you are consoling "post" at wrong place. Try outputting it just before return statement.