0

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?

2 Answers 2

1

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), ...
Sign up to request clarification or add additional context in comments.

Comments

0

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'])
    }
  })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.