反应查询突变:API调用失败时,通过onError回调从服务器获取响应

问题描述

我正在做一个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: () => {
      
    }
  })

正如您在评论中看到的那样,我正在尝试读取onError回调中从服务器返回的字段。我该怎么办?

解决方法

users: [{ "color": "red" },{ "color": "blue" }]

let [ createItem ] = useMutation(payload => createItem(payload),{ onSuccess: (response) => { },onError: (error) => { console.log(error.response.data); console.log(error.response.status); },onMutate: () => { } }) 内进行console.log(error)时并不清楚,但是onError应该可用。

,

它应该可以正常工作。确保您的 HTTP 客户端(可能是 Axios)配置为抛出错误。例如:

import axios from 'axios'
import { useMutation } from 'react-query'
import { BASE_URL } from 'constants/api'

const client = axios.create({
  baseURL: BASE_URL,})

const request = (options) => {
  const onSuccess = (response) => response
  const onError = (error) => {
    // Throwing an error here
    throw error
  }
  return client(options).then(onSuccess).catch(onError)
}

const { mutate } = useMutation(
  async (data) =>
    await request({
      url: '/someUrl',method: 'post',data
    }),{ onError: (e) => console.log(e) }
  )

当然,最好将您的 Axios 设置存储在单独的文件中,然后只需导入正在使用突变的“请求”变量。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...