T
TanStack11mo ago
narrow-beige

Best Practice for mutationFn Return Value When Not Using Axios

I'm working with mutations in React Query and need clarification on the optimal return value from mutationFn. The type definition shows: mutationFn: (variables: TVariables) => Promise<TData> My main question is: Should I return the promise directly (e.g., return response.json()) or should I await response.json() first and then return the final data inside mutationFn?
const mutationFn = async (variables) => {
const response = await fetch('/api/endpoint', {
method: 'POST',
body: JSON.stringify(variables)
})
return await response.json();
// vs
return response.json();
}
const mutationFn = async (variables) => {
const response = await fetch('/api/endpoint', {
method: 'POST',
body: JSON.stringify(variables)
})
return await response.json();
// vs
return response.json();
}
I'm asking this question because I’ve noticed that examples on the internet differ on how they return data in a mutationFn. What are the practical and logical differences between these approaches? Are there any implications for error handling or the way React Query processes the mutation results? Thanks in advance for any insights!
3 Replies
rare-sapphire
rare-sapphire11mo ago
there's no difference, if you return a promise inside an async function it will wait for the result no await is shorter
narrow-beige
narrow-beigeOP11mo ago
So when we return await response.json() we are returning the final JSON data, but since we are returning from async, it's still a Promise. So when we return the final data, what are awaiting at the end? I mean, will React Query "await" the final JSON data? If we just return the response.json(), I can understand that React Query will await the parsing of the JSON.
rare-sapphire
rare-sapphire11mo ago
nothing about this is specific to React Query, it's just how async functions work if you return a promise the promise you get from calling the async function will resolve to whatever your original promise resolved to

Did you find this page helpful?