React 查询突变:当 API 调用失败时使用 onError 回调从服务器获取响应

Wai*_*ein 2 mutation reactjs react-query

我正在做一个 React JS 项目。在我的项目中,我使用 React 查询https://react-query.tanstack.com/docs/guides/mutations。我正在使用突变向服务器发出发布请求。但是当 API 调用失败并返回 onError 时,我正在尝试从服务器获取响应返回。

这是我的代码。

let [ createItem ] = useMutation(payload => createItem(payload), {
    onSuccess: (response) => {
      
    },
    onError: (error) => {
      // here I am trying to get the response. In axios, we can do something like error.data.server_error_code
    },
    onMutate: () => {
      
    }
  })
Run Code Online (Sandbox Code Playgroud)

正如您在评论中看到的那样,我试图在 onError 回调中读取从服务器返回的字段。我怎样才能做到这一点?

cas*_*hol 5

let [ createItem ] = useMutation(payload => createItem(payload), {
    onSuccess: (response) => {
      
    },
    onError: (error) => {
      console.log(error.response.data);
      console.log(error.response.status);
    },
    onMutate: () => {
      
    }
})
Run Code Online (Sandbox Code Playgroud)

只做console.log(error)inside时并不完全清楚onError,但error.response应该可用。