React-query :: Mutations

query์™€ ๋‹ค๋ฅด๊ฒŒ CUD์— ์‚ฌ์šฉ๋œ๋‹ค.

https://react-query.tanstack.com/guides/mutations

 

Mutations

Subscribe to our newsletter The latest TanStack news, articles, and resources, sent to your inbox.

react-query.tanstack.com

 

์‚ฌ์šฉ์˜ˆ์ œ

const mutation = useMutation(newTodo => axios.post('/todos', newTodo))
return (
     <div>
       {mutation.isLoading ? (
         'Adding todo...'
       ) : (
         <>
           {mutation.isError ? (
             <div>An error occurred: {mutation.error.message}</div>
           ) : null}

           {mutation.isSuccess ? <div>Todo added!</div> : null}

           <button
             onClick={() => {
               mutation.mutate({ id: new Date(), title: 'Do Laundry' })
             }}
           >
             Create Todo
           </button>
         </>
       )}
     </div>
   )

์ƒํƒœ๋‚˜ return data๋Š” useQuery์™€ ๊ฐ™์Œ

  • mutation.mutate ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ๋ณ€์ˆ˜๋ฅผ mutation์— ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋‹ค.
// This will not work in React 16 and earlier
 const CreateTodo = () => {
   const mutation = useMutation(event => {
     event.preventDefault()
     return fetch('/api', new FormData(event.target))
   })

   return <form onSubmit={mutation.mutate}>...</form>
 }

return๋œ error๋‚˜ data๋ฅผ clear ํ•  ๋•Œ๋Š” mutation์˜ reset ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

๋ฐ˜์‘ํ˜•