如何取消RTK Query请求

发布于 2025-01-21 06:14:40 字数 601 浏览 2 评论 0原文

我正在使用RTK查询来处理我的请求。但是我在取消请求时遇到问题。

场景是这样的,我有一种模式可以显示一个表格来添加todo,但是当用户想要关闭模式时,请求应取消,如果该请求尚待审理。

const [addTodo, { isLoading }] = useAddTodoMutation();

const onSubmit = async (values: ToDo) => {
     try {
      await addTodo(values).unwrap();
      console.log('Successful')
    } catch (error) {
      console.log('failed')
    }
  };

我知道有一个中止可以取消突变,例如addtodo(values).abort();,我们可以在useffect用<<<中使用它。代码> useref 。

是否可以编写一种通用方式或自定义钩子来包装我的所有突变并处理组件被卸载时处理取消请求?

I am using the RTK query to handle my requests. But I have a problem canceling requests.

The scenario is like this, I have a modal to show a form to add a todo but, when users want to close the modal the request should be canceled if it is pending yet.

const [addTodo, { isLoading }] = useAddTodoMutation();

const onSubmit = async (values: ToDo) => {
     try {
      await addTodo(values).unwrap();
      console.log('Successful')
    } catch (error) {
      console.log('failed')
    }
  };

I know there is an abort to cancel mutation like addTodo(values).abort(); and we can use it in useEffect cleanup with useRef.

Is it possible to write a general way or a custom hook to wrap all my mutations and handle canceling requests when a component will be unmounted?

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

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

发布评论

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

评论(3

南冥有猫 2025-01-28 06:14:40

这样做几乎没有任何价值。如果您的请求待定,只要您不在前几毫秒内,该请求已经发送到服务器,客户端只是在等待响应。即使您取消该请求并且服务器上的数据可能已经更改,服务器也将继续处理该请求。因此,通常让请求完成,然后使所有缓存数据(通常是通过换取)无效,这些数据可能会因突变而改变。

如果取消请求,则不会发生无效。

也就

const request = myTriggerFunction()

// ...

request.abort()

There is hardly any value in doing that. If your request is pending, as long as you are not within the first few milliseconds, that request has already been sent to the server and the client is just waiting for the response. The server will keep processing that request even if you cancel it and data on the server is probably already changed. So it usually makes sense to let the request finish and then invalidate all cache data (usually, by refetching) that has potentially been changed by the mutation.

If you cancel the request, invalidation will not happen.

All that said: if you triggered your mutation with myTriggerFunction(), you can do

const request = myTriggerFunction()

// ...

request.abort()
调妓 2025-01-28 06:14:40

您可以使用自定义钩子包装突变:

const { useMyMutation } = dataHandlerApi;

const timeout = 5000;

export const useMyMutationWithTimeout = () => {
  const [trigger, data] = useMyMutation();

  const triggerWithTimeout = (args) => {
    const request = trigger(args);

    setTimeout(() => request?.abort(), timeout);
  };

  return [triggerWithTimeout , data];
};

You can use custom hook to wrap mutation:

const { useMyMutation } = dataHandlerApi;

const timeout = 5000;

export const useMyMutationWithTimeout = () => {
  const [trigger, data] = useMyMutation();

  const triggerWithTimeout = (args) => {
    const request = trigger(args);

    setTimeout(() => request?.abort(), timeout);
  };

  return [triggerWithTimeout , data];
};
臻嫒无言 2025-01-28 06:14:40

假设您将更新用户:

const [updateUser, { isLoading }] = useUpdateUserMutation();

const updateCurrentUser = async (values) => {

     try {
        const response = await updateUser(...).unwrap();
        /...../
     } catch (e) {
       console.log(e);
     }

您可以致电:

updateUser()?.abort();

从组件中的任何位置或将功能注入其他组件

Let's say that you will update the user:

const [updateUser, { isLoading }] = useUpdateUserMutation();

const updateCurrentUser = async (values) => {

     try {
        const response = await updateUser(...).unwrap();
        /...../
     } catch (e) {
       console.log(e);
     }

You can call:

updateUser()?.abort();

From any place in your component or inject the function into other components

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文