React

React Query Handle Delete Request with useMutation Tutorial

Pinterest LinkedIn Tumblr

To handle a DELETE request with useMutation in a React Query application, you would first need to set up a mutation hook using the useMutation function from the react-query library. This hook takes in a callback function that performs the actual DELETE request and returns an object containing the status, data, error, and mutate properties.

Here’s an example of how you might use the useMutation hook to handle a DELETE request:

Copy codeimport { useMutation } from 'react-query'

function DeleteTodo({ id }) {
  const [mutate, { status }] = useMutation(() => {
    return axios.delete(`/todos/${id}`)
  })

  return (
    <button onClick={() => mutate()}>
      {status === 'loading' ? 'Deleting...' : 'Delete Todo'}
    </button>
  )
}

In this example, the DeleteTodo component takes in an id prop, which is passed to the useMutation hook. The callback function passed to useMutation performs a DELETE request to the /todos/:id endpoint using the axios library. The status of the mutation is then used to update the text on the button to indicate whether the request is currently in progress or not.

You can also use the returned data and error from the mutation to handle the response and errors accordingly.

Copy codeconst [mutate, { status, data, error }] = useMutation(() => {
    return axios.delete(`/todos/${id}`)
  })

You can also use the onSuccess,onError callbacks to handle the response and error accordingly.

Copy codeconst [mutate, { status, data, error }] = useMutation(() => {
    return axios.delete(`/todos/${id}`)
  }, {
    onSuccess: (data) => {
      console.log("delete success",data)
    },
    onError: (error) => {
      console.log("error",error)
    }
  })

You can also refresh the query after successful mutation using refetchQueries option of useMutation

Copy codeconst [mutate, { status, data, error }] = useMutation(() => {
    return axios.delete(`/todos/${id}`)
  }, {
    onSuccess: (data) => {
      console.log("delete success",data)
    },
    onError: (error) => {
      console.log("error",error)
    },
    refetchQueries: ['todos']
  })

Write A Comment