Reputation: 39
I want to call console.log(email)
in onError
part of react-query useMutation
Hook. However, the ''
value is output to console.
Looking at the code, if an isError
error is occurring, we put text into setEmail
, and after onError
occurs, we print console.log(email)
.
If I take a console.log(email)
, it is being called with an empty value, but I want to print "hi isError"
.
The logic is that when button is clicked, handleSocialLogin
mutate function is called, isError
is mounted in useEffect
, then setEmail("hi isError")
is saved in isError
, then console.log(email)
is being called in onError
part.
export const googleLogin = (data: any) => {
return axios.post("/login/google", data).then(({ data }) => data as any);
};
const [email, setEmail] = useState<string>("");
const { mutate, isLoading, isError } = useMutation(googleLogin, {
onError(error: AxiosError) {
console.log(email);
},
});
useEffect(() => {
if (isError) {
setEmail("hi isError");
}
}, [isError]);
function handleSocialLogin(event: React.MouseEvent<HTMLElement> & any) {
mutate({
clientIp: "hi",
});
}
return <button onClick={handleSocialLogin}>button</button>;
Upvotes: 2
Views: 377
Reputation: 845
The onError would execute at almost the same time as the isError
change in the mutation hook. The useEffect
is detecting the isError
change and then executes, which means it will happen after the onError
.
You can try this if you want to console the result.
export const googleLogin = (data: any) => {
return axios.post("/login/google", data).then(({ data }) => data as any);
};
const [email, setEmail] = useState<string>("");
const { mutate, isLoading, isError } = useMutation(googleLogin, {
onError(error: AxiosError) {
setEmail("hi isError");
},
});
useEffect(() => {
if (isError) {
console.log(email);
}
}, [isError, email]);
function handleSocialLogin(event: React.MouseEvent<HTMLElement> & any) {
mutate({
clientIp: "hi",
});
}
return <button onClick={handleSocialLogin}>button</button>;
Upvotes: 1