Repository navigation
refactor(mosaic): extract the debounced password check into useDebouncedAsync #10065
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b4b50fe
refactor(mosaic): move password check timing into the form hook
alexcarpenter eca67cb
refactor(mosaic): extract the debounced password check into useDeboun…
alexcarpenter 771629f
fix(mosaic): tell a failed check apart from an empty result in useDeb…
alexcarpenter 8164c30
docs(mosaic): note that useDebouncedAsync compares value by reference
alexcarpenter 7ebf853
test(mosaic): reject inside the check so the rejection is handled
alexcarpenter File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| --- | ||
| --- |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
136 changes: 136 additions & 0 deletions
136
packages/mosaic/src/hooks/__tests__/use-debounced-async.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { act, renderHook } from '@testing-library/react'; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { deferred } from '../../__tests__/async'; | ||
| import { useDebouncedAsync } from '../use-debounced-async'; | ||
|
|
||
| const DELAY = 300; | ||
|
|
||
| interface Props { | ||
| value: string; | ||
| enabled?: boolean; | ||
| } | ||
|
|
||
| function setup(run: (value: string, options: { signal: AbortSignal }) => Promise<string>, initial: Props) { | ||
| return renderHook(({ value, enabled }: Props) => useDebouncedAsync(value, run, { delayMs: DELAY, enabled }), { | ||
| initialProps: initial, | ||
| }); | ||
| } | ||
|
|
||
| describe('useDebouncedAsync', () => { | ||
| beforeEach(() => { | ||
| vi.useFakeTimers(); | ||
| }); | ||
| afterEach(() => { | ||
| vi.useRealTimers(); | ||
| }); | ||
|
|
||
| it('runs only the latest value once it stops changing', async () => { | ||
| const run = vi.fn((value: string) => Promise.resolve(`checked ${value}`)); | ||
| const { result, rerender } = setup(run, { value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY - 1)); | ||
| rerender({ value: 'ab' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY - 1)); | ||
| expect(run).not.toHaveBeenCalled(); | ||
| expect(result.current.isPending).toBe(true); | ||
| await act(() => vi.advanceTimersByTimeAsync(1)); | ||
| expect(run).toHaveBeenCalledExactlyOnceWith('ab', { signal: expect.any(AbortSignal) }); | ||
| expect(result.current).toEqual({ data: 'checked ab', error: undefined, isError: false, isPending: false }); | ||
| }); | ||
|
|
||
| it('keeps the last result while the next value is checked', async () => { | ||
| const run = vi.fn((value: string) => Promise.resolve(`checked ${value}`)); | ||
| const { result, rerender } = setup(run, { value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| rerender({ value: 'b' }); | ||
| expect(result.current).toEqual({ data: 'checked a', error: undefined, isError: false, isPending: true }); | ||
| }); | ||
|
|
||
| it('aborts and ignores a check that is overtaken by a new value', async () => { | ||
| const first = deferred<string>(); | ||
| const signals: AbortSignal[] = []; | ||
| const run = vi.fn((value: string, { signal }: { signal: AbortSignal }) => { | ||
| signals.push(signal); | ||
| return value === 'a' ? first.promise : Promise.resolve('checked b'); | ||
| }); | ||
| const { result, rerender } = setup(run, { value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| rerender({ value: 'b' }); | ||
| expect(signals[0]?.aborted).toBe(true); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| await act(async () => { | ||
| first.resolve('checked a'); | ||
| await first.promise; | ||
| }); | ||
| expect(result.current.data).toBe('checked b'); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ['rejects', () => Promise.reject(new Error('down'))], | ||
| [ | ||
| 'throws', | ||
| () => { | ||
| throw new Error('down'); | ||
| }, | ||
| ], | ||
| ])('reports an error when the check %s', async (_, run) => { | ||
| const { result } = setup(run, { value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| expect(result.current).toEqual({ data: undefined, error: new Error('down'), isError: true, isPending: false }); | ||
| }); | ||
|
|
||
| it('reports a failure even when the check rejects without a reason', async () => { | ||
| const { result } = setup( | ||
| () => { | ||
| const check = deferred<string>(); | ||
| check.reject(); | ||
| return check.promise; | ||
| }, | ||
| { value: 'a' }, | ||
| ); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| expect(result.current.isError).toBe(true); | ||
| }); | ||
|
|
||
| it('clears the result and cancels pending work when disabled', async () => { | ||
| const run = vi.fn((value: string) => Promise.resolve(`checked ${value}`)); | ||
| const { result, rerender } = setup(run, { value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| rerender({ value: 'b', enabled: false }); | ||
| expect(result.current).toEqual({ data: undefined, error: undefined, isError: false, isPending: false }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| expect(run).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it('does not restart when the check function changes identity', async () => { | ||
| const calls: string[] = []; | ||
| const { rerender } = renderHook( | ||
| ({ value }: Props) => | ||
| useDebouncedAsync( | ||
| value, | ||
| v => { | ||
| calls.push(v); | ||
| return Promise.resolve(v); | ||
| }, | ||
| { delayMs: DELAY }, | ||
| ), | ||
| { initialProps: { value: 'a' } }, | ||
| ); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY - 1)); | ||
| rerender({ value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(1)); | ||
| expect(calls).toEqual(['a']); | ||
| }); | ||
|
|
||
| it('aborts a running check on unmount', async () => { | ||
| const signals: AbortSignal[] = []; | ||
| const run = (_: string, { signal }: { signal: AbortSignal }) => { | ||
| signals.push(signal); | ||
| return new Promise<string>(() => {}); | ||
| }; | ||
| const { unmount } = setup(run, { value: 'a' }); | ||
| await act(() => vi.advanceTimersByTimeAsync(DELAY)); | ||
| unmount(); | ||
| expect(signals[0]?.aborted).toBe(true); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| import { useEffect, useRef, useState } from 'react'; | ||
|
|
||
| export interface DebouncedAsyncOptions { | ||
| /** Wait this long after the last change before running. */ | ||
| delayMs: number; | ||
| /** When `false`, clears the result and cancels any waiting or running check. Defaults to `true`. */ | ||
| enabled?: boolean; | ||
| } | ||
|
|
||
| export interface DebouncedAsyncResult<TData> { | ||
| data: TData | undefined; | ||
| error: unknown; | ||
| isError: boolean; | ||
| isPending: boolean; | ||
| } | ||
|
|
||
| interface Settled<TValue, TData> { | ||
| value: TValue; | ||
| data: TData | undefined; | ||
| error: unknown; | ||
| isError: boolean; | ||
| } | ||
|
|
||
| /** | ||
| * Runs `run(value)` once `value` has stopped changing for `delayMs`, and returns the latest result. | ||
| * The previous result stays visible while the next one is pending. A new value, disabling or | ||
| * unmounting aborts the `signal` and drops any result that arrives afterwards. | ||
| * | ||
| * `value` is compared with `Object.is`, so it must be referentially stable across renders. An | ||
| * object or array created during render (such as an un-memoized `[]` or `{}`) counts as a new | ||
| * value every render and restarts the debounce. Pass a primitive or memoize it. | ||
| * | ||
| * @example | ||
| * const strength = useDebouncedAsync(password, (value, { signal }) => checkStrength(value, { signal }), { | ||
| * delayMs: 300, | ||
| * enabled: password !== '', | ||
| * }); | ||
| */ | ||
| export function useDebouncedAsync<TValue, TData>( | ||
| value: TValue, | ||
| run: (value: TValue, options: { signal: AbortSignal }) => Promise<TData>, | ||
| { delayMs, enabled = true }: DebouncedAsyncOptions, | ||
| ): DebouncedAsyncResult<TData> { | ||
| const runRef = useRef(run); | ||
| const [settled, setSettled] = useState<Settled<TValue, TData>>(); | ||
|
|
||
| useEffect(() => { | ||
| runRef.current = run; | ||
| }); | ||
|
|
||
| useEffect(() => { | ||
| if (!enabled) { | ||
| setSettled(undefined); | ||
| return; | ||
| } | ||
| const controller = new AbortController(); | ||
| const settle = (result: Omit<Settled<TValue, TData>, 'value'>) => { | ||
| if (!controller.signal.aborted) { | ||
| setSettled({ value, ...result }); | ||
| } | ||
| }; | ||
| const timer = setTimeout(() => { | ||
| void Promise.resolve() | ||
| .then(() => runRef.current(value, { signal: controller.signal })) | ||
| .then( | ||
| data => settle({ data, error: undefined, isError: false }), | ||
| (error: unknown) => settle({ data: undefined, error, isError: true }), | ||
| ); | ||
| }, delayMs); | ||
| return () => { | ||
| clearTimeout(timer); | ||
| controller.abort(); | ||
| }; | ||
| }, [value, enabled, delayMs]); | ||
|
|
||
| if (!enabled) { | ||
| return { data: undefined, error: undefined, isError: false, isPending: false }; | ||
| } | ||
| return { | ||
| data: settled?.data, | ||
| error: settled?.error, | ||
| isError: settled?.isError === true, | ||
| isPending: settled === undefined || !Object.is(settled.value, value), | ||
| }; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NIT: This comment could be a bit clearer on the fact that
valueneeds to be referentially stable across renders and passing in un-memoized[]or{}etc is not supported and will treat every render as a changed value.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good call, spelled that out in the JSDoc.