令牌刷新后,组件不会根据跟进请求重新呈现

Component doesn't re-render on follow up request after token refresh

这是我的 axios-hoook.js,我正在使用 axios-hooks 包。

import useAxios from 'axios-hooks';
import axios from 'axios';
import LocalStorageService from './services/local-storage.service';
import refreshToken from './refresh-token';

axios.defaults.baseURL = 'http://localhost:3000/api/v1';
axios.defaults.transformResponse = [
  (responseData) => {
    const { data, error } = JSON.parse(responseData);
    return error || data;
  },
];

// request interceptor to add token to request headers
axios.interceptors.request.use(
  async (config) => {
    const token = LocalStorageService.getAccessToken();
    if (token) {
      config.headers = {
        authorization: token,
      };
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// response interceptor intercepting 401 responses, refreshing token and retrying the request
axios.interceptors.response.use(
  (response) => response,
  (error) => {
    const { config } = error;
    if (error.response?.status === 401 && !config._retry) {
      config._retry = true;
      refreshToken(LocalStorageService.getRefreshToken())
        .then((res) => {
          const { accessToken } = res.data.data;
          LocalStorageService.setAccessToken(accessToken);
          return axios(config);
        })
        .catch((err) => {
          if (err.response.status === 401) {
            LocalStorageService.setUser(null);
            window.location.href = '/login';
          }
          return Promise.reject(err);
        });
    }
    return Promise.reject(error);
  }
);

export default useAxios;

这是Course.jsx使用它的地方。

const Course = () => {
const [{ data: courses = [] }, refetchCourse] = axiosHook(ApiConfig.COURSE.GET_COURSES.url);

return (
  <Datatable
    entity={entity}
    columns={courseColumns}
    rows={courses}
    deleteRow={handleDeactivate}
    viewRow={handleView}
  />
 )
}

Image

在 axios-hooks 文档中有一个 link 用于实现刷新令牌功能的工作示例。在这个 link https://codesandbox.io/s/axios-hooks-authentication-zyeyh.

的 CodeSandbox 中是 运行

将其与您的示例进行比较,您会发现您的示例不起作用的原因。

我的代码有错误。我没有回报承诺。

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    const { config } = error;
    if (error.response?.status === 401 && !config._retry) {
      config._retry = true;
      return refreshToken(LocalStorageService.getRefreshToken()) // this line
        .then((res) => {
          const { accessToken } = res.data.data;
          LocalStorageService.setAccessToken(accessToken);
          return axios(config);
        })
        .catch((err) => {
          if (err.response.status === 401) {
            LocalStorageService.setUser(null);
            window.location.href = '/login';
          }
          return Promise.reject(err);
        });
    }
    return Promise.reject(error);
  }
);