如何破坏突变反应查询中的错误?

发布于 2025-02-08 14:44:55 字数 1294 浏览 0 评论 0原文

我想从我

const getMutationService = () => {
  return {
    editProfile: async (
      displayName: string,
      privateProfile?: boolean,
    ): Promise<AuthEditMeResponse | undefined> => {
      try {
        const result = await userApi.mePost({
          payload: {
            display_name: displayName,
            _private: privateProfile,
          },
        });
        return result;
      } catch (error) {
        console.log("User Edit Profile Error", error);
      }
    },
  };
};

const useUserProfile = () => {
  const queryClient = useQueryClient();
  const queryService = getQueryService();
  // const { data, isLoading } = useQuery('auth', queryService.login)
  const mutationService = getMutationService();

  const editProfileData = async (
    displayName: string,
    privateProfile?: boolean,
  ): Promise<AuthEditMeResponse | void> => {
    try {
      return await mutationService.editProfile(displayName, privateProfile);
    } catch (error) {
      console.log(error);
    }
  };

  return editProfileData;
};

export default useUserProfile;

现在在这里创建的React-Query突变服务挂钩返回错误,我只是返回结果,这是成功的结果,但是我要求的API端点也要求返回我必须需要的错误状态代码用于我的前端组件。

我如何从我创建的此GetMutationservice Hook中返回isloading,数据或错误?相反,目前,它仅返回对我的组件的成功响应。

I want to return error from react-query mutation service hook I've created here

const getMutationService = () => {
  return {
    editProfile: async (
      displayName: string,
      privateProfile?: boolean,
    ): Promise<AuthEditMeResponse | undefined> => {
      try {
        const result = await userApi.mePost({
          payload: {
            display_name: displayName,
            _private: privateProfile,
          },
        });
        return result;
      } catch (error) {
        console.log("User Edit Profile Error", error);
      }
    },
  };
};

const useUserProfile = () => {
  const queryClient = useQueryClient();
  const queryService = getQueryService();
  // const { data, isLoading } = useQuery('auth', queryService.login)
  const mutationService = getMutationService();

  const editProfileData = async (
    displayName: string,
    privateProfile?: boolean,
  ): Promise<AuthEditMeResponse | void> => {
    try {
      return await mutationService.editProfile(displayName, privateProfile);
    } catch (error) {
      console.log(error);
    }
  };

  return editProfileData;
};

export default useUserProfile;

Right now I am only returning the result, which is the successful result, however the API endpoint I am requesting to also returns error status codes that I must need and use for my front end component.

How can I return isLoading, data, or error from this getMutationService hook i've created? Instead currently its only returning successful responses to my component.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南风起 2025-02-15 14:44:56

您可以在捕获块中丢弃错误,例如:

try { //... }
catch(e) {
  throw Error(e);
}

当您在组件中调用功能时,捕获块内部可以执行类似的操作:

try { //... }
catch(e) {
  setError(e.message);
}

显示错误消息。

You can throw the errors inside the catch blocks, like this:

try { //... }
catch(e) {
  throw Error(e);
}

And when you invoke the function in your component, inside the catch block you can do something like:

try { //... }
catch(e) {
  setError(e.message);
}

to show the error message.

掩于岁月 2025-02-15 14:44:56

问题在于您正在捕获突变函数内部的错误。当您遇到错误时,例如用于记录,它将被转换为a 解决的承诺。这与React-Query无关,这就是承诺(分别尝试/捕捉异步)的工作方式。

React-Query希望您返回A 拒绝的承诺,以便它可以陷入错误状态。为此,您可以:

  • 不是 在突变中捕获错误 - 只要让它们起泡到反应引物即可。这是推荐的方法。如果要记录错误,请使用提供的OnError回调。
  • 捕获错误后重新出现错误。

The problem is that you are catching the error inside the mutation function. When you catch an error, e.g. for logging, it will be transformed into a resolved Promise. This has nothing to do with react-query, this is how promises (resp. try/catch with async-await) work.

react-query expects you to return a rejected Promise so that it can go into error state. To do this, you can either:

  • not catch errors in the mutationFn - just let them bubble up to react-query. This is the recommended approach. If you want error logging, use the provided onError callback.
  • re-throw the error after catching it.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文