I have a form in React App and use React Query for mutation data in this array of posts:
constPOSTS=[{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><divclassName="block"><labelhtmlFor="title">Title</label><inputname="title"id="title"type="text"></input></div><divclassName="block"><labelhtmlFor="author">Author</label><inputname="author"id="author"type="text"></input></div><buttontype="submit">AddNew</button></form>
1.Add onSubmit handler for Form
<formonSubmit={(e)=>{e.preventDefault();newPostMutation.mutate(newFormData(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.
constnewPostMutation=useMutation({mutationKey:["addNewPost"],// key - a unique name for this particular mutationmutationFn:async(postFromForm)=>{constnewPost=Object.fromEntries(postFromForm);returnawaitwait(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)
For further actions, you may consider blocking this person and/orreporting abuse