2

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>;

2
  • Why don't you simply put setEmail("hi isError") in the onError? Commented Dec 28, 2022 at 4:16
  • @Hao-JungHsieh If I set setEmail('hi error') as onError and run console.log(email) in onError , '' is called with empty value. Commented Dec 28, 2022 at 5:02

1 Answer 1

1

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>;

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.