30 lines
792 B
TypeScript
30 lines
792 B
TypeScript
import { debounce } from '$shared/lib/utils';
|
|
|
|
export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
|
let immediate = $state(initialValue);
|
|
let debounced = $state(initialValue);
|
|
|
|
const updateDebounced = debounce((value: T) => {
|
|
debounced = value;
|
|
}, wait);
|
|
|
|
return {
|
|
get immediate() {
|
|
return immediate;
|
|
},
|
|
set immediate(value: T) {
|
|
immediate = value;
|
|
// Manually trigger the debounce on write
|
|
updateDebounced(value);
|
|
},
|
|
get debounced() {
|
|
return debounced;
|
|
},
|
|
reset(value?: T) {
|
|
const resetValue = value ?? initialValue;
|
|
immediate = resetValue;
|
|
debounced = resetValue;
|
|
},
|
|
};
|
|
}
|