Usestate Async Problem (not Updating/saving)
Here's my code: useEffect(() => { fetchPosts() }, []) const [posts, setPosts] = useState([]) const fetchPosts = async () => { const data = await fetch('https://json
Solution 1:
setPosts sets the data asynchronously. That is why the console.log
statement gets executed even before the setPosts finishes its job of setting the fetched content.
You can do this instead.
importReact, { useEffect, useState } from"react";
import"./styles.css";
exportdefaultfunctionApp() {
useEffect(() => {
fetchPosts();
}, []);
const [posts, setPosts] = useState([]);
const fetchPosts = async () => {
const data = awaitfetch(
"https://jsonplaceholder.typicode.com/posts?_limit=10"
);
const posts_data = await data.json();
setPosts(posts_data);
setImmediate(() => {
console.log(posts);
})
};
return (
<divclassName="App"><h1>Hello CodeSandbox</h1><h2>Start editing to see some magic happen!</h2></div>
);
}
UPDATE: You can do this for mapping out the posts...
<divclassName="container-fluid mt-3"><h1className="text-white">Posts</h1><div>{posts && posts.map(post => {
return <p>asdasd</p>
})}</div></div>
Post a Comment for "Usestate Async Problem (not Updating/saving)"