将拦截器与react-query一起使用

Mis*_*hko 5 interceptor reactjs axios react-query

我的应用程序中有很多自定义react-query挂钩,例如:

export const useItems = () => {
  return useQuery(["items"], async () => {
    const response = await axios.get("/api/items");

    if (response.status !== 200) {
      throw response.data.error ?? "Unknown error";
    }

    return response.data;
  });
}

export const useVenueSearch = (placeId) => {
  return useQuery(["places", placeId], async () => {
    const response = await axios.get(`/api/places/${placeId}`);

    if (response.status !== 200 && response.status !== 404) {
      throw response.data.error ?? "Unknown error";
    }

    return response.data;
  });
}

...
Run Code Online (Sandbox Code Playgroud)

在任何时间点,在任何这些自定义挂钩 API 调用中,服务器都可能决定用户需要接受新的条款和条件才能继续使用该产品。在这种情况下,服务器返回已知的 4xx 响应。

集中处理此 4xx 响应并更新 React 状态(以显示要求用户接受条款和条件的模式)的最佳方法是什么?


奖励问题(类似场景)

给定一堆自定义突变钩子,我想引入一个人为延迟,这样请求就不会在 1000 毫秒过去之前完成。放置此逻辑的最佳中心位置是什么?

Adh*_*tal 1

你可以使用axios提供的拦截器,甚至可以使用它的重试方法再次访问API。

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });
Run Code Online (Sandbox Code Playgroud)

你可以在这里读更多关于它的内容。https://axios-http.com/docs/interceptors 但除此之外,您需要创建自己的包装器来完成这部分,但react-query没有提供拦截器。