Created
August 28, 2024 16:10
-
-
Save gioragutt/3a6b5df8e2bc96f42b5b7500d88a1a58 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function setAbortableTimeout( | |
callback: (...args: any[]) => void, | |
delayInMilliseconds: number, | |
signal: AbortSignal, | |
...args: any[] | |
) { | |
if (!signal) { | |
return setTimeout(callback, delayInMilliseconds, ...args); | |
} | |
signal?.addEventListener('abort', handleAbort); | |
// Setup our internal timer that we can clear-on-abort. | |
const timeoutHandle = setTimeout(internalCallback, delayInMilliseconds, ...args); | |
function internalCallback() { | |
signal?.removeEventListener('abort', handleAbort); | |
callback(); | |
} | |
function handleAbort() { | |
clearTimeout(timeoutHandle); | |
} | |
return timeoutHandle; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
useEffect(() => { | |
const controller = new AbortController(); | |
const uniqueResponses = [...new Map(responses.map(response => [hashQueryKey(response[0]), response])).values()]; | |
uniqueResponses.forEach(([key, data, options = {}]) => { | |
const { delay = -1 } = options; | |
const setQueryData = () => queryClient.setQueryData(key, data); | |
if (delay > 0) { | |
setAbortableTimeout(() => queryClient.setQueryData(key, data), delay, controller.signal); | |
return; | |
} | |
setQueryData(); | |
}); | |
return () => { | |
controller.abort(); | |
queryClient.clear(); | |
}; | |
}, [queryClient, responses]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment