← All tasksReact · Senior
Search without race conditions
Write a useSearch(query, search) hook. search(query) returns a promise of an array of results. The hook returns { results, loading }: while a request is in flight, loading is true.
Responses may arrive in a different order than the requests were sent. Only the result for the current query should be shown: a stale response that arrives later must not overwrite it. For an empty query - results = [] without calling search.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (4)
const search = (q) => Promise.resolve([q + '1']); const { result } = renderHook(({ q }) => useSearch(q, search), { initialProps: { q: 'a' } }); await waitFor(() => expect(result.current.results).toEqual(['a1'])); expect(result.current.loading).toBe(false);
const search = () => new Promise(() => {}); const { result } = renderHook(({ q }) => useSearch(q, search), { initialProps: { q: 'a' } }); await waitFor(() => expect(result.current.loading).toBe(true));
const pending = {}; const search = (q) => new Promise((resolve) => { pending[q] = resolve; }); const { result, rerender } = renderHook(({ q }) => useSearch(q, search), { initialProps: { q: 'a' } }); await waitFor(() => expect(typeof pending.a).toBe('function')); rerender({ q: 'ab' }); await waitFor(() => expect(typeof pending.ab).toBe('function')); pending.ab(['AB']); await waitFor(() => expect(result.current.results).toEqual(['AB'])); pending.a(['A']); await wait(30); expect(result.current.results).toEqual(['AB']);
const search = fn(() => Promise.resolve(['x'])); const { result } = renderHook(({ q }) => useSearch(q, search), { initialProps: { q: '' } }); await wait(30); expect(search).toHaveBeenCalledTimes(0); expect(result.current.results).toEqual([]); expect(result.current.loading).toBe(false);