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 함수를 사용하면 된다.

반응형