T
TanStack15mo ago
national-gold

Debounced Autosave

Hi everyone, I have an app where I’m trying to implement an autosave. Each time a user enters input into one of many input fields, I want to update the data across the application. However, I want to debounce the actual mutation and proceeding cache invalidation so it only happens five seconds after the data has stopped changing. What is the best way to go about this?
3 Replies
optimistic-gold
optimistic-gold15mo ago
First you need to create a debounce fn that will debounce any fn you provide to it Then use this function on mutation.mutate like this
const debouncedMutate = debounce(mutation.mutate, 5000)
const debouncedMutate = debounce(mutation.mutate, 5000)
Second argument is timeout value after which your original mutate will be called
provincial-silver
provincial-silver15mo ago
useDebounceCallback
Custom hook that creates a debounced version of a callback function.
provincial-silver
provincial-silver15mo ago
The nice thing about something like useDebounceCallback is it'll be cleaned up whenever your component(s) unmount, and if you desire you can flush() if you need

Did you find this page helpful?