How to return data from Tanstack React Query useMutation?
Asked Answered
G

2

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!

Gnash answered 24/1, 2023 at 13:27 Comment(0)
S
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!
}


Simmons answered 24/1, 2023 at 13:35 Comment(1)
thank you, the issue was the await in "await createUser({ user: user, accessToken: accessToken });"Gnash
M
8

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

Marrin answered 26/4, 2023 at 15:35 Comment(0)
S
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!
}


Simmons answered 24/1, 2023 at 13:35 Comment(1)
thank you, the issue was the await in "await createUser({ user: user, accessToken: accessToken });"Gnash

© 2022 - 2024 — McMap. All rights reserved.