I have a form in React App and use React Query for mutation data in this array of posts:
const POSTS = [
{ id: 1, title: "Green Olly", author: "Garry Molland" },
{ id: 2, title: "Fargus the Greatest", author: "Mazzy Fazzy" },
];
I want to send new post information from the HTML form with the new title and author.
<form >
<div className="block">
<label htmlFor="title">Title</label>
<input name="title" id="title" type="text"></input>
</div>
<div className="block">
<label htmlFor="author">Author</label>
<input name="author" id="author" type="text"></input>
</div>
<button type="submit" >AddNew</button>
</form>
1.Add onSubmit handler for Form
<form onSubmit={(e)=> {
e.preventDefault();
newPostMutation.mutate(new FormData(e.target));
}}>
We create new FormData object with From data and prevent Form's standard "action".
2.In our newPostMutation we use useMutation hook because of mutation of the original array of Posts.
const newPostMutation = useMutation({
mutationKey: ["addNewPost"],
// key - a unique name for this particular mutation
mutationFn: async (postFromForm) => {
const newPost = Object.fromEntries(postFromForm);
return await wait(1000).then(()=> POSTS.push({id: crypto.randomUUID(), title: newPost.title, author: newPost.author}))},
onSuccess: () => {
qClient.invalidateQueries(["posts"]);
}
})
postFromForm parameter in async gets new FormData(e.target), then we use Object.fromEntries()transforms a list of key-value pairs into an object. Then we use newPost object to add its properties to pushing object to the Posts array.
wait(1000) function for simulation API work
Top comments (0)