conaticus
conaticus

Reputation: 461

mutateAsync data is undefined in submit event (react query)

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

Upvotes: 1

Views: 9282

Answers (1)

TkDodo
TkDodo

Reputation: 28793

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.

Upvotes: 1

Related Questions