T
TanStack3y ago
afraid-scarlet

Spacing network requests with `useMutation`

We have an audio player, each second a mutation sends a POST to persist the user's progression. We don't really need to be that precise, and it would be ok for us to only send that post every 5 or 10s. Something like this might work:
const mutation = useMutation((progress) => {
if(progress % 5) { // only posts every 5sec
postToApi(progress)
}
}, {
onMutate: (newProgress) => {
// cancel queries...
// ignore errors and update locally regardless
queryClient.setQueryData(key, newProgress);
}
});
const mutation = useMutation((progress) => {
if(progress % 5) { // only posts every 5sec
postToApi(progress)
}
}, {
onMutate: (newProgress) => {
// cancel queries...
// ignore errors and update locally regardless
queryClient.setQueryData(key, newProgress);
}
});
Is there a better way to do this ?
1 Reply
rising-crimson
rising-crimson3y ago
How are you calling mutate? I'd keep conditional logic like that out of the mutation function and instead consider a form of throttling outside of the context of TanStack Query

Did you find this page helpful?