I'm fetching a list of post from a local server and then updated it with a form, but after submitting the list doesn't update, it must be reloaded to update the list. I tried adding a counter state and place it on my second parameter in UseEffect, it worked but sometimes it won't. Is there a best way to keep up to date my list with the server without reloading?
here is my code
function App() {
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
getPosts();
}, []);
const getPosts = async () => {
const response = await axios.get("/posts");
const { data } = response;
setPosts(data);
};
return (
<div className="App">
<Navbar />
<Route
exact
path="/"
component={() => <Posts posts={posts} getPosts={getPosts} />}
/>
<Route exact path="/add" render={() => <Form />} />
</div>
);
}
export default App;
const Posts = ({ posts, getPosts }) => {
console.log("Render POSTS");
// const { posts } = React.useContext(postsContext);
return (
<div style={{ display: "flex" }}>
{posts.map((post, idx) => (
<Post
title={post.title}
description={post.description}
key={idx}
id={post._id}
getPosts={getPosts}
/>
))}
</div>
);
};
const Form = ({ getPosts }) => {
const [title, titleChange, resetTitle] = InputHooks();
const [description, descriptionChange, resetDescription] = InputHooks();
// const { renderToggle } = React.useContext(postsContext);
async function submitForm() {
const response = await axios.post("/posts", { title, description });
const { data } = response;
console.log(data.message);
}
return (
<form>
<div>
<label htmlFor="title">Title</label>
<input
name="title"
id="title"
value={title}
onChange={titleChange}
></input>
</div>
<div>
<label htmlFor="description">Description</label>
<textarea
name="description"
id="description"
value={description}
onChange={descriptionChange}
></textarea>
</div>
<button
onClick={async (e) => {
e.preventDefault();
submitForm();
resetTitle();
resetDescription();
}}
>
Submit
</button>
</form>
);
Thanks for the answer guys, I finally solved it using async function. I use await on submitPost
and followed by getPosts()
, so each submit I will await until the submit
completes and then getPost
. My first time mistake was putting the await
on getPosts
.
Can you try this: React.useEffect(() => { getPosts(); }, [posts]);
we place posts in here in useEffect so that whenever that variable changes, it will re-render the whole component.
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.