dommer
dommer

Reputation: 19810

Why is my react-query mutation always "successful"?

I'm trying to make a react-query mutation (using axios, but I get the same behavior if I switch to the fetch API).

I set it up like this.

const mutation = useMutation(
    () => {
      axios.post("http://swapi.dev/api/foobar", {});
    },
    {
      onSuccess: () => {
        console.log("success");
      },
      onError: () => {
        console.log("error");
      },
    }
  );

The URL can be anything that fails. I've tried it on the real API I'm using, returning both 500 and 404 errors.

I fire the mutation as follows.

mutation.mutate();

Every time I get "success" displayed in the console. The onError handler never fires. The calls return the expected errors when viewed in Chrome's network tab (and display console errors).

I'm using react-query 3.3.6 and axios 0.21.1 (both the latest release versions).

Can anyone point me in the right direction?

Upvotes: 1

Views: 4450

Answers (1)

Dennis Martinez
Dennis Martinez

Reputation: 6512

useMutation first parameter expects a function which returns a promise. This is known as the mutation function. Instead of returning a promise, you're returning a void. You'll want to either use async/await or return the promise from axios.

const mutation = useMutation(
  () => {
    return axios.post('http://swapi.dev/api/foobar', {})
  },
  {
    onSuccess: () => {
      console.log('success')
    },
    onError: () => {
      console.log('error')
    }
  }
)

Upvotes: 6

Related Questions