React-query 到可重用钩子中,axios 返回错误 400

问题描述 投票:0回答:1

尝试将

react-query
axios
一起使用来创建可重用的钩子以进行状态管理。

import { useMutation } from "react-query";

import axios from "axios";

const API_URL: string = process.env.REACT_APP_API_URL!;

console.log(API_URL);

export const useLoginMutation = () =>
  useMutation((user: { email: string; password: string }) => {
    return axios.post(
      `${API_URL}/api/v1/users/login`,
      { user },
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
  });

// Component.tsx

mutateUser.mutate({ email: data.email, password: data.password });

错误:

enter image description here

但是登录详细信息是正确的。就好像变量没有调用 API

reactjs typescript axios react-query
1个回答
0
投票

您遇到的错误似乎是来自声明突变钩子的方式。这是更新的代码。

const useUserLogin = () => {
    const queryClient = useQueryClient();
    const loginUser = useMutation({
      mutationFn: (data: { email: string; password: string }) => {
        return axios.post(
          `${API_URL}/api/v1/users/login`,
          { ...data },
          {
            headers: {
              "Content-Type": "application/json",
            },
          }
        );
      },
      onSuccess: () => {
        queryClient.invalidateQueries({ queryKey: ["userData"] });
      },
    });
    return { loginUser };

    const { loginUser } = useUserLogin();

    const handleLogin = async(data:{ email: string; password: string })=>{
        try {
          await loginUser.mutateAsync({...data})
        } catch (error) {
          return error
        }
    }

© www.soinside.com 2019 - 2024. All rights reserved.