Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

GenIl
GenIl

Posted on

FormData from Form in mutation!

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"},];
Enter fullscreen modeExit fullscreen mode

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>
Enter fullscreen modeExit fullscreen mode

1.Add onSubmit handler for Form

<formonSubmit={(e)=>{e.preventDefault();newPostMutation.mutate(newFormData(e.target));}}>
Enter fullscreen modeExit fullscreen mode

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"]);}})
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp