| 269 | } |
| 270 | |
| 271 | function atomWithThrottle<T>(initialValue: T, delayMilliseconds = 500): AtomWithThrottle<T> { |
| 272 | // DO NOT EXPORT currentValueAtom as using this atom to set state can cause |
| 273 | // inconsistent state between currentValueAtom and throttledValueAtom |
| 274 | const _currentValueAtom = atom(initialValue); |
| 275 | |
| 276 | const throttledValueAtom = atom(initialValue, (get, set, update: SetStateAction<T>) => { |
| 277 | const prevValue = get(_currentValueAtom); |
| 278 | const nextValue = typeof update === "function" ? (update as (prev: T) => T)(prevValue) : update; |
| 279 | set(_currentValueAtom, nextValue); |
| 280 | throttleUpdate(get, set); |
| 281 | }); |
| 282 | |
| 283 | const throttleUpdate = throttle(delayMilliseconds, (get: Getter, set: Setter) => { |
| 284 | const curVal = get(_currentValueAtom); |
| 285 | set(throttledValueAtom, curVal); |
| 286 | }); |
| 287 | |
| 288 | return { |
| 289 | currentValueAtom: atom((get) => get(_currentValueAtom)), |
| 290 | throttledValueAtom, |
| 291 | }; |
| 292 | } |
| 293 | |
| 294 | function atomWithDebounce<T>(initialValue: T, delayMilliseconds = 500): AtomWithDebounce<T> { |
| 295 | // DO NOT EXPORT currentValueAtom as using this atom to set state can cause |