【问题标题】:How do I get the HTTP response code from a successful React query?如何从成功的 React 查询中获取 HTTP 响应代码?
【发布时间】:2021-04-12 13:59:46
【问题描述】:

如何从成功的 React 查询中获取状态码?

这是我的自定义钩子:

const validateIban = async (accountId, encodedIban) => {
    await axios
        .post(`${CUSTOMER_PORTAL_API}/policy/accounts/${accountId}/iban/${encodedIban}`)
};

export function useValidateIban(accountId) {
    return useMutation(encodedIban => validateIban(accountId, encodedIban));
}

这就是我使用 mutate 的钩子的地方:

const validateIbanQuery = useValidateIban(accountId)


validateIbanQuery.mutate(encodeURIComponent(iban), {
        onSuccess: () => {
          ******HERE I WANT THE STATUS CODE (204, 202 e.g.)******
        },
        onError: (error) => {
          if (error.response.status === 400) {
            ....
          }
          if (error.response.status === 403) {
            ....
          }
        }
      })

【问题讨论】:

    标签: reactjs axios react-query


    【解决方案1】:

    onSuccess回调的第一个参数是AxiosResponse

    axios.post("/api/data", { text }).then(response => {
      console.log(response.status)
      return response; // this response will be passed as the first parameter of onSuccess
    });
    
    onSuccess: (data) => {
      console.log(data.status);
    },
    

    现场演示

    【讨论】:

    • 这导致数据未定义:(
    • @btrautmann 我配置axios-mock-adapter时没有返回数据,现在应该修复了。你可以简单地返回axios.post(...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 2023-02-22
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多