【问题标题】:React JS React Query's useMutation: Unable to retrieve the response from the server within the onError callbackReact JS React Query 的 useMutation:无法在 onError 回调中从服务器检索响应
【发布时间】:2020-11-17 13:03:22
【问题描述】:

我正在开发一个 React JS 项目。我正在使用 React 查询 https://react-query.tanstack.com/ 发出 API 请求。当 API 抛出 422 或 400 或 401 等时,我现在在 onError 回调中从服务器检索响应数据时遇到突变问题。

这是我的突变。

let [ createProductMutation, { data, error } ] = useMutation((payload) => createProduct(payload), {
    onMutate: () => {
      
    },
    onSuccess: (response) => {
      
    },
    onError: (err, variables, snapshotValue) => {
      //err is not the response from the server.
    }
  })

正如您在 onError 回调中看到的,无法从服务器检索响应。

数据和错误(createProductMutation 旁边的那个)也不是来自服务器的响应。

我试过用这个。

  try {
       let response = await createProductMutation(data);
        // response from the API is not here too, "response"
    } catch (e) {
        // response from the API is not here too
    }

如何在 onError 回调中检索响应?

【问题讨论】:

  • 你有想过这个吗?我将我的反应查询分成不同的文件以保持模块化。我无法返回错误消息。而不是在控制台中引发错误。

标签: reactjs react-query


【解决方案1】:
let [ createItem ] = useMutation(payload => createItem(payload), {
  onError: (error) => {
    console.log(error.response.data);
    console.log(error.response.status);
  }
})

对我来说,上述解决方案有效!在onError 内部,error.response 应该是可用的。

【讨论】:

    【解决方案2】:

    要获得响应,您需要将错误转换为 json,然后等待承诺。请参阅下面的示例,其中“消息”是您的后端为响应消息返回的任何内容。

    onError: async (error, variables, context) => {
        const errorObj = error;
        const errorObjAsJSON = await errorObj.json();
        const { message } = errorObjAsJSON;
        console.log(message);
      },
    

    你显然可以进一步压缩

    onError: async (error, variables, context) => {
            const errorObj = await error.json();
            const { message } = errorObj;
            console.log(message);
          },
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 2021-11-29
      • 2023-01-24
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2022-06-16
      • 2021-07-09
      相关资源
      最近更新 更多