1

I am currently trying to make a request to my API using React Query. When I log my data inside the component function scope it logs fine and gives the data I expect, it also logs the correct data before the handleSubmit does. When I log my data variable inside handleSubmit, after submitting, it always logs undefined.

// useSignup.ts

import axios from "axios";
import { useMutation } from "react-query";

const signup = (credidentials: any) => {
    return axios.post("/api/signup", credidentials);
};

const useSignup = () => {
    return useMutation(signup);
};

export default useSignup;
// Signup.tsx

const {
    mutateAsync: makeApiRequest,
    isLoading,
    isSuccess,
    isError,
    data: authData,
} = useSignup();

console.log(authData); // Updates fine and gives the correct data

const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    await makeApiRequest(input);
    console.log(authData); // Always undefined
};

1 Answer 1

1

because awaiting makeApiRequest does not, in the same event handler, make data from the hook "defined" right after that. It's similar to:

const [count, setCount] = React.useState(undefined)

<button onClick={() => {
  setCount(1)
  console.log(count)
}) />

here, logging the count will also be undefined, as it will only be set to 1 in the next render cycle. being async doesn't change that - this is just how react works.

if you want to access data after a successful submit, use the onSuccess callback of the mutate function:

makeApiRequest(input, { onSuccess: newData => console.log(newData) }

you can also use mutateAsync, which returns data from the mutation, but you need to catch errors manually and I don't think this is needed often.

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

1 Comment

Thank you very much. Someone answered exactly same somewhere else just a second ago. Appreciate the help!

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.