尝试将
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 });
错误:
但是登录详细信息是正确的。就好像变量没有调用 API
您遇到的错误似乎是来自声明突变钩子的方式。这是更新的代码。
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
}
}