T
TanStack2y ago
helpful-purple

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
dependent-tan
dependent-tan2y 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
passive-yellow
passive-yellow2y ago
useDebounceCallback
Custom hook that creates a debounced version of a callback function.
passive-yellow
passive-yellow2y 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?