Flush the debounced Redux handler on unmount

Ensure that pending changes are written to the store instead of discarding them.
This commit is contained in:
Philipp Stracker 2024-10-24 12:49:20 +02:00
parent 317ba4e8ec
commit 046e3d5699
No known key found for this signature in database

View file

@ -18,20 +18,20 @@ export const useDebounceField = (
) => {
const [ fieldValue, setFieldValue ] = useState( storeValue );
// Memoize the debounced store sync
// Memoize the debounced store sync.
const debouncedSync = useMemo(
() => debounce( syncToStore, delay ),
[ syncToStore, delay ]
);
// Sync field with store changes
// Sync field with store changes.
useEffect( () => {
if ( storeValue !== '' && fieldValue !== storeValue ) {
setFieldValue( storeValue );
}
}, [ storeValue, fieldValue ] );
// Handle field updates and store sync
// Handle field updates and store sync.
const updateField = useCallback(
( newValue ) => {
setFieldValue( newValue );
@ -40,10 +40,10 @@ export const useDebounceField = (
[ debouncedSync ]
);
// Cleanup on unmount
// Cleanup on unmount.
useEffect( () => {
return () => {
debouncedSync.cancel();
debouncedSync?.flush();
};
}, [ debouncedSync ] );