Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in react-query mutateAsync

I am learning react-query and I want to use the mutateAsync in the useMutation API. Here is my code:

import { useMutation } from "react-query";

const asyncCall = () => {
  return new Promise((resolve, reject) =>
    setTimeout(() => reject("reject"), 1000)
  );
};

const Home = () => {
  const { mutateAsync } = useMutation(asyncCall);

  const handleClick = async () => {
    try {
      const res = await mutateAsync();
    } catch (err) {
      console.log("catch error"); // output: catch error
    }
  };

  return (
    <div>
      <button onClick={() => handleClick()}>Click</button>
    </div>
  );
};

export default Home;

Now my code can successfully catches the error returns from the asyncCall, but I see a warning in my console:

enter image description here

details:

enter image description here

So it says the error comes from the handleClick function, but I thought the try...catch already taken care of the error? Why there is a warning? How can I fix it?

I made a demo here.

Thank you!

like image 551
Shiqi Avatar asked Oct 20 '25 09:10

Shiqi


1 Answers

per default, react-query logs all errors to the console. If you don’t want that, you can override setLogger: https://react-query.tanstack.com/reference/setLogger

import { setLogger } from 'react-query'

setLogger({
  log: console.log,
  warn: console.warn,
  error: () => {}, // do nothing
})
like image 50
TkDodo Avatar answered Oct 21 '25 23:10

TkDodo