如何设置自定义错误消息React查询

rlcwz9us  于 2022-10-15  发布在  React
关注(0)|答案(1)|浏览(132)

我使用useMutation挂钩将数据发布到后端。我需要呈现从后端收到的错误消息。我似乎无法正确地分解错误消息。

export const postStuff = () => {
    return useMutation(
        async (token) =>
            await axios({
                url: foo,
                method: "post",
                data: { token },
            }),
        {
            onError: (error) => {
                console.log(error.response.data);
                // custom error message received successfully here
            }
        }
    );
};`
const {
        mutateAsync,
        isError: postStuffIsError, // boolean works fine
        error 
    } = postStuff();

console.log(error?.message) // Request failed with status code 400 but I want my custom error message from the BE
y1aodyip

y1aodyip1#

错误数据与在onError回调中发生的方式相同,可以在error?.response.data上访问,而不是在error?.message上访问。
因此,您可以使用:

console.log("error message:", error?.message);
console.log("error response data:", error?.response.data); // the actual data

请参见executable codesandbox demo here。相关代码如下:

export default function App() {
  const usePostStuff = () => {
    return useMutation(
      () => {
        // request below should return 400 due to missing password
        return axios.post("https://reqres.in/api/login", { email: "a@a" });
      },
      {
        onError: (error) => {
          console.log("Mutation Failed:", error);
          console.log(error.response.data);
          // custom error message received successfully here
        },
        onSuccess(data) {
          console.log("Mutation Succesful:", data);
        },
        onSettled() {
          console.log("Mutation completed.");
        }
      }
    );
  };

  const {
    mutateAsync,
    isError: postStuffIsError, // boolean works fine
    error,
    isLoading,
    isSuccess
  } = usePostStuff();

  console.log("error message:", error?.message);
  console.log("error response data:", error?.response.data);

  return (
    <div className="App">
      <h1>useMutations() Hook</h1>
      <button
        onClick={() => {
          mutateAsync();
        }}
      >
        Execute Mutation here and watch the console
      </button>
      {isLoading && <p>Making request...</p>}
      {isSuccess && <p>Todo added!</p>}
      {postStuffIsError && <p>There was an error! {}</p>}
    </div>
  );
}

在边注上,您将看到我将postStuff重命名为usePostStuff。这是一个重要的惯例:

**我必须以“Use”开头命名我的自定义Hook吗?**请这样做。这个会议是非常重要的。如果没有它,我们就不能自动检查是否违反了钩子规则,因为我们无法知道某个函数内部是否包含对钩子的调用。

相关问题