React

How to Use React Query Mutation to Create or Add Data to Server

Pinterest LinkedIn Tumblr

To use React Query’s useMutation hook to create or add data to a server, 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 POST 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 POST request to create a new todo:

Copy codeimport { useMutation } from 'react-query'

function CreateTodo({ newTodo }) {
  const [mutate, { status }] = useMutation(() => {
    return axios.post('/todos', newTodo)
  })

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

In this example, the CreateTodo component takes in a newTodo prop, which is passed as the second argument to the axios.post function, when the button is clicked, the mutate function is called, which triggers the POST request to the server, and 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.post('/todos', newTodo)
  })

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

Copy codeconst [mutate, { status, data, error }] = useMutation(() => {
    return axios.post('/todos', newTodo)
  }, {
    onSuccess: (data) => {
      console.log("create 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.post('/todos', newTodo)
  }, {
    onSuccess: (data) => {
      console.log("create success",data)
    },
    onError: (error) => {
      console.log("error",error)
    },
    refetchQueries: ['todos']
  })

It’s important to note that you will need to handle the server side validation and error handling as well.

Write A Comment