Auto update post list
Answered
Clumber Spaniel posted this in #help-forum
Clumber SpanielOP
how can i make so when i for example create a new post(it gets saved in db) in a modal popup in my nextjs app, and the posts are listed inside page(in react usestate) the modal is in too, the listing gets automatically updated?
Answered by B33fb0n3
you can use react query for example and invalidate the specific query. Like that it automatically updates the state and your list is updated without you need to worry about anything
4 Replies
@Clumber Spaniel how can i make so when i for example create a new post(it gets saved in db) in a modal popup in my nextjs app, and the posts are listed inside page(in react usestate) the modal is in too, the listing gets automatically updated?
you can use react query for example and invalidate the specific query. Like that it automatically updates the state and your list is updated without you need to worry about anything
Answer
I wanna believe you want the most React-y way to do this. In Next.js there are many ways you can do this, depending if your use case requires to be fully client side.
You can do this by having a Server Action that will handle the mutation (creating a new post) and this server action returns the newly created post, then update your local state with the previous posts + the new one. You can call the Server Action from an event handler, when you click a button or when you submit a form.
Worth noting that if you do this manually you will encounter many possible problems like Race Conditions, lack of loading states, error states, having your local state in sync with the latest server state, etc. I would also recommend implementing React Query for client side fetching and mutations which will handle all these annoying problems out of the box.
You can do this by having a Server Action that will handle the mutation (creating a new post) and this server action returns the newly created post, then update your local state with the previous posts + the new one. You can call the Server Action from an event handler, when you click a button or when you submit a form.
Worth noting that if you do this manually you will encounter many possible problems like Race Conditions, lack of loading states, error states, having your local state in sync with the latest server state, etc. I would also recommend implementing React Query for client side fetching and mutations which will handle all these annoying problems out of the box.
Clumber SpanielOP
yes, thanks for mentioning react query, i wanted to take a look at it for some time now, and this gave me the final reason :)