8

I have a form, and I want to return the id from the newly created object which I'm creating through Axios via a REST API.

I'm integrating Tanstack Query, using the useMutation hook. I've created my own hook so I can use the mutation code throughout my react application.

const useCreateUser = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ user, accessToken }: createUserInputs) =>
      createUser(user, accessToken),
    onSuccess: (data) => {
      console.log(data)
    },
  });
};

Console.log(data) is working.

I'm declaring the hook like this:

const { data:createduser, mutate: createUser } = useCreateUser();

and calling the hook like this:

await createUser({ user: user, accessToken: accessToken });

but this is not returning the data.

Where am I going wrong!

2 Answers 2

13

You can use mutateAsync instead of mutate. mutateAsync will return the value.

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

Comments

4

You should get returning data from data useMutations props:

const { data:createduser, mutate: createUser, isSuccess } = useCreateUser();

createUser({ user: user, accessToken: accessToken });
if (isSuccess) {
    console.log(createduser); // data here!
}

1 Comment

thank you, the issue was the await in "await createUser({ user: user, accessToken: accessToken });"

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.