T
TanStack2y ago
ambitious-aqua

Showing a message if a request is taking a long time

Hello, I'm trying to do something like show a message if a request (in this case, a mutation), is taking a long time. This is what I have so far:
export const useExampleHook = () => {
const timerRef = useRef<ReturnType<typeof setTimeout>>();

const exampleMutation = useMutation({
mutationFn: (data: ExampleDataType) =>
typedMockRequest<ExampleDataType>({
data,
timeout: 8000,
}),
onMutate: () => {
timerRef.current = setTimeout(() => {
show('This is taking a while...'); // makes a toast appear with message
}, 5000);
},
onSettled: () => {
clearTimeout(timerRef.current);
},
});

useEffect(() => {
return () => clearTimeout(timerRef.current);
}, []);

return {
exampleMutation
};
}
export const useExampleHook = () => {
const timerRef = useRef<ReturnType<typeof setTimeout>>();

const exampleMutation = useMutation({
mutationFn: (data: ExampleDataType) =>
typedMockRequest<ExampleDataType>({
data,
timeout: 8000,
}),
onMutate: () => {
timerRef.current = setTimeout(() => {
show('This is taking a while...'); // makes a toast appear with message
}, 5000);
},
onSettled: () => {
clearTimeout(timerRef.current);
},
});

useEffect(() => {
return () => clearTimeout(timerRef.current);
}, []);

return {
exampleMutation
};
}
So far it seems to work. If the request is longer than 5s (in this case I'm faking an 8s request using the typedMockRequest function), it will create a toast using the show method. But it seems a little dirty and I'm not sure if there is a better approach to observing the total time a mutation or query is taking to fire off some sort of error message like this.
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?