React 查询使用Query & Axios

问题描述 投票:0回答:1

我正在尝试在 React Query 和 Axios 的帮助下创建一个 API 函数。 当我将 useQuery 与 vanilla fetch 函数一起使用时 - 一切都很完美。

export const useGetDebts = async () => {
  const { families } = appStore.user;
  const res = useQuery("getDebts", async () => {
    const res = await fetch(`${API_URL}/api/family/${families[0]}/debts`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${appStore.token ?? ""}`,
      },
    });
    const parsedBody: DebtsResponse = await res.json();
    return parsedBody;
  });
  return res;
};

但是当我将普通的 fetch 函数切换到 Axios 时 - 我收到错误状态 500(不确定它是来自 React Query 还是 Axios)。

export const useGetDebts = async () => {
  const { families } = appStore.user;
  const res = useQuery("getDebts", async () => {
    const res = await axiosInstance.get<DebtsResponse>(`/api/family/${families[0]}/debts`);
    return res.data;
  });
  return res;
};

预先感谢您的任何解释/建议。

P.s. axiosInstance 与 useMutation 钩子一起工作得很好。所以这只会让我更加困惑。 =(

export const useGetDebt = () => (
  useMutation(async (id: number) => {
    const { families } = appStore.user;
    const res = await axiosInstance.get<DebtResponse>(`/api/family/${families[0]}/debts/${id}`);
    return res.data;
  })
);

P.s.s.如果有某种相关的话,我正在使用 React Native。

reactjs react-native axios fetch react-query
1个回答
0
投票

react-query 不会给你任何 500 错误,因为react-query 不执行任何数据获取。它只需要从 queryFn 返回的 Promise 并为您管理异步状态。

我不确定

fetch
代码是否真的有效,因为它不处理任何错误。
fetch
不会像
axios
那样将错误的状态代码(如 4xx 或 5xx)转换为失败的 Promise。您需要检查
response.ok

 useQuery(['todos', todoId], async () => {
   const response = await fetch('/todos/' + todoId)
   if (!response.ok) {
     throw new Error('Network response was not ok')
   }
   return response.json()
 })

请参阅 与 fetch 和其他默认情况下不会抛出异常的客户端一起使用

所以我最好的猜测是,

fetch
示例还为您提供了 500 错误代码,但您没有将该错误转发给react-query。

© www.soinside.com 2019 - 2024. All rights reserved.