Aranan Wijayasooria
Aranan Wijayasooria

Reputation: 1

React query useMutation + axios post keeps returning data as "undefined"

I'm new to react-query. I'm trying to use it along with axios to post data, and while the data in the backend is updated successfully, react query keeps outputting data as undefined which is a problem because I'm trying to get feedback from the API call

const {mutate, isLoading} = useMutation(() => {postFunction(rowData)}, {

      onSuccess: data => {
        console.log(data)
        alert(data['message'])
      },
      onError: data => {
        alert(data['message'])
      }
  })

For context the axios function used to post the data looks like the following:

 async function editEventLines(data){
      const response = await axios.post(`/api/saleOrders/updateEvent`, {data: data, pk:id})
      console.log(response.data)
      return response.data
    }

The mutate function from useMutation is called via a button component in React:

<Button loading = {isLoading} disabled = {disabled} onClick = {mutate}> Save Changes </Button>      

If you see the console.log statements, it seems as though console.log in the useMutation function is called before the console.log in the axios function on the console, which is why I think data is coming out as undefined. Do you guys know why I'm having this issue?

Upvotes: 0

Views: 2141

Answers (2)

rodd
rodd

Reputation: 11

You should always return from your mutationFn.

const {mutate, isLoading} = useMutation({
    mutationfn : (rowdata) => {
        return postFunction(rowdata)
    },
    // Or just write :
    // mutationFn : postFunction,

    onSuccess: data => {
        console.log(data)
        alert(data['message'])
    },

    onError: data => {
        alert(data['message'])
    }
  })

Upvotes: 0

Tomas Vancoillie
Tomas Vancoillie

Reputation: 3878

You should return your mutation function in the useMutation hook. By wrapping it in brackets, the function doens't return a promise and it should as described in the docs.

... = useMutation(() => postFunction(rowData), ...

Upvotes: 1

Related Questions