DoneDeal0
DoneDeal0

Reputation: 6257

How to handle error in react-query's onSuccess event?

I have an api call made with React Query's useMutation. Once the call is done, I store the data in indexedDB. This process is done inside the onSuccess parameter of useMutation.

In firefox, the process always fails. So I need to throw an error and let the user know that this browser is not supported. But React Query doesn't catch the error anymore inside the onSuccess method. How to fix this? Here is the code:

// the mutation
const login: AuthService["login"] = () => {
  const { mutateAsync, isLoading, error, reset, isSuccess } = useMutation( 
  (form: LoginForm) => _login(form),
    {
      onSuccess: async (user: User) => {
        await IndexedDB.saveUser(user);
      },
    }
  );

  return {
    onLogin: (form: LoginForm) => mutateAsync(form),
    loading: isLoading,
    reset: () => reset(),
    serverError: error ? error["message"] : "",
    success: isSuccess,
  };
};

// the indexedDb function (the first part, this why the naming is different):
  static createDB() {
    const request = indexedDB.open(DB_NAME, 1);
    request.onupgradeneeded = (e: IDBVersionChangeEvent) => {
      const db = e.target["result"];
      return db.createObjectStore(MY_STORE, { autoIncrement: true });
    };
    request.onerror = () => { 
      throw new Error("this browser is not supported"); // error not caught
    };
  }

Upvotes: 1

Views: 2509

Answers (1)

TkDodo
TkDodo

Reputation: 28843

Easiest way would likely to make it part of the mutationFn, in your case, _login(form). You can just normally await your mutation there and after that save to IndexedDB.

Upvotes: 1

Related Questions