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:

const POSTS = [
  { id: 1, title: "Green Olly", author: "Garry Molland" },
  { id: 2, title: "Fargus the Greatest", author: "Mazzy Fazzy" },
];
Enter fullscreen mode Exit fullscreen mode

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

1.Add onSubmit handler for Form

 <form onSubmit={(e)=> {
        e.preventDefault();
        newPostMutation.mutate(new FormData(e.target));
        }}>
Enter fullscreen mode Exit 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.

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

πŸ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay