doc(createDeboucnedState): add JSDoc for createDebouncedState
This commit is contained in:
@@ -1,5 +1,28 @@
|
|||||||
import { debounce } from '$shared/lib/utils';
|
import { debounce } from '$shared/lib/utils';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates reactive state with immediate and debounced values.
|
||||||
|
*
|
||||||
|
* Useful for UI inputs that need instant feedback but debounced logic
|
||||||
|
* (e.g., search fields with API calls). The immediate value updates on
|
||||||
|
* every change for UI binding, while debounced updates after a delay.
|
||||||
|
*
|
||||||
|
* @param initialValue - Initial value for both immediate and debounced state
|
||||||
|
* @param wait - Delay in milliseconds before updating debounced value (default: 300)
|
||||||
|
* @returns Object with immediate/debounced getters, immediate setter, and reset method
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```svelte
|
||||||
|
* <script lang="ts">
|
||||||
|
* const search = createDebouncedState('', 300);
|
||||||
|
* </script>
|
||||||
|
*
|
||||||
|
* <input bind:value={search.immediate} />
|
||||||
|
*
|
||||||
|
* <p>Typing: {search.immediate}</p>
|
||||||
|
* <p>Searching: {search.debounced}</p>
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
||||||
let immediate = $state(initialValue);
|
let immediate = $state(initialValue);
|
||||||
let debounced = $state(initialValue);
|
let debounced = $state(initialValue);
|
||||||
@@ -9,6 +32,7 @@ export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
|||||||
}, wait);
|
}, wait);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
/** Current value with immediate updates (for UI binding) */
|
||||||
get immediate() {
|
get immediate() {
|
||||||
return immediate;
|
return immediate;
|
||||||
},
|
},
|
||||||
@@ -17,9 +41,14 @@ export function createDebouncedState<T>(initialValue: T, wait: number = 300) {
|
|||||||
// Manually trigger the debounce on write
|
// Manually trigger the debounce on write
|
||||||
updateDebounced(value);
|
updateDebounced(value);
|
||||||
},
|
},
|
||||||
|
/** Current value with debounced updates (for logic/operations) */
|
||||||
get debounced() {
|
get debounced() {
|
||||||
return debounced;
|
return debounced;
|
||||||
},
|
},
|
||||||
|
/**
|
||||||
|
* Resets both values to initial or specified value.
|
||||||
|
* @param value - Optional value to reset to (defaults to initialValue)
|
||||||
|
*/
|
||||||
reset(value?: T) {
|
reset(value?: T) {
|
||||||
const resetValue = value ?? initialValue;
|
const resetValue = value ?? initialValue;
|
||||||
immediate = resetValue;
|
immediate = resetValue;
|
||||||
|
|||||||
Reference in New Issue
Block a user