T
TanStack•2y ago
sunny-green

Access Mutation Data

Hello Guys, What is the best way to access data returned by a mutation?
const mutation = useMutation({ mutationFn: useCreateInvitation });
const mutation = useMutation({ mutationFn: useCreateInvitation });
export const useCreateInvitation = async (values: CreateInvitationFormData) => {
const { token, ...data } = values
return await axios.post(BACKEND_URL + '/project/invite', data, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: "Bearer " + token
},
});
};
export const useCreateInvitation = async (values: CreateInvitationFormData) => {
const { token, ...data } = values
return await axios.post(BACKEND_URL + '/project/invite', data, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: "Bearer " + token
},
});
};
This functions returns the new created invitation
const values = {
email,
role,
projectId,
token,
};

mutation.mutateAsync(values, {
onError: () => {
toast.error('Something went wrong!');
return null;
},
});
const values = {
email,
role,
projectId,
token,
};

mutation.mutateAsync(values, {
onError: () => {
toast.error('Something went wrong!');
return null;
},
});
I tried mutation.data.data but it doesnt always works. Also i dont know if its better to access in the onSuccess Function or just after the block. Does anyone know a reliable way to access this returned data. Thanks in advance
4 Replies
sunny-green
sunny-greenOP•2y ago
I thing i got it. is this the best way?:
mutation.mutateAsync(values, {
onSuccess: (data) => {
console.log('DATA: ', data.data.id);
},
onError: () => {
toast.error('Something went wrong!');
return null;
},
});
mutation.mutateAsync(values, {
onSuccess: (data) => {
console.log('DATA: ', data.data.id);
},
onError: () => {
toast.error('Something went wrong!');
return null;
},
});
conscious-sapphire
conscious-sapphire•2y ago
Depends on what you want to do. OnSuccess only gives you a callback. Mutation.data gives you the option to use it in a component.
sunny-green
sunny-greenOP•2y ago
I just need the data returned from rhe mutation since i need the id for a email that will be sent So i guess this is the best way I got now
conscious-sapphire
conscious-sapphire•2y ago
Yeah, that should work 🙂

Did you find this page helpful?