如何使用 React + React Query + Axios 堆栈创建全局 401 未授权处理程序?

How to create a global 401 unauthroized handler using React + ReactQuery + Axios stack?

所以我构建前端的方式是将绑定到单个资源的每个 API 操作封装在自定义挂钩中,如下所示:

export default function useSubjects() {
  const queryClient: QueryClient = useQueryClient();
  const token: string | null = useStore((state) => state.user.token);
  const { yearCourseId } = useParams<{ yearCourseId: string }>();

  const getSubjects = async () => {
    const response = await axios.get(`yearCourses/${yearCourseId}/subjects`, {
      headers: { Authorization: `Bearer ${token}` },
    });
    return response.data;
  };

  const postSubject = async (subject: SubjectType) => {
    const response = await axios.post(`yearCourses/${yearCourseId}/subjects`, subject, {
      headers: { Authorization: `Bearer ${token}` },
    });
    return response.data;
  };

  const query = useQuery(SUBJECTS_QUERY_KEY, getSubjects);

  const postMutation = useMutation(postSubject, {
    onSuccess: (subject: SubjectType) => {
      queryClient.setQueryData(SUBJECTS_QUERY_KEY, (old: any) => [...old, subject]);
    },
  });

  return { query, postMutation };
}

现在全局处理的方法是什么401 unauthorized?我想在每个未经授权的请求上将用户导航到 /login。请注意,我有更多像这样的挂钩与其他资源相关联。

使用 onError 回调。您也可以在 queryCache

上作为回调在全局范围内执行此操作
const queryClient = new QueryClient({
 queryCache: new QueryCache({
   onError: error => {
     // check for 401 and redirect here
   }
 })
})