【问题标题】:How to handle error in react-query's onSuccess event?如何处理 react-query 的 onSuccess 事件中的错误?
【发布时间】:2021-05-06 17:37:50
【问题描述】:

我有一个使用 React Query 的 useMutation 进行的 api 调用。通话完成后,我将数据存储在indexedDB 中。这个过程在useMutationonSuccess参数内完成。

在 Firefox 中,进程总是失败。所以我需要抛出一个错误,让用户知道这个浏览器不被支持。但是 React Query 在 onSuccess 方法中不再捕获错误。如何解决这个问题?代码如下:

// 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
    };
  }

【问题讨论】:

    标签: javascript reactjs indexeddb react-query


    【解决方案1】:

    最简单的方法可能是使其成为mutationFn 的一部分,在您的情况下为_login(form)。您通常可以在那里 await 您的突变,然后保存到 IndexedDB。

    【讨论】:

      猜你喜欢
      • 2021-09-10
      • 1970-01-01
      • 2022-11-12
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2021-10-10
      • 2018-12-07
      相关资源
      最近更新 更多