React JS React Query 的 useMutation:无法在 onError 回调中从服务器检索响应

Wai*_*ein 5 reactjs react-query

我正在开发一个 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.
    }
  })
Run Code Online (Sandbox Code Playgroud)

正如您在 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
    }
Run Code Online (Sandbox Code Playgroud)

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

小智 2

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

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

显然你可以进一步压缩它

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