Recipes/Debounced search
Debounced search
A search box whose query lives in the URL: the input follows every keystroke, the URL changes 300 ms after the last one, and Clear is immediate.
import type { QubeeListHandle } from '@qubeejs/react';
import type { articleList } from './article-list';
/** How long typing must pause before the URL changes. */const SEARCH_DEBOUNCE_MS = 300;
/** * The article search box. It shows the draft, so it never lags; it navigates * 300 ms after the last keystroke, replacing the history entry; Clear goes out * at once. */export function ArticleSearch({ list }: { list: QubeeListHandle<typeof articleList> }) { return ( <div role="search"> <label htmlFor="article-search">Search articles</label> <input id="article-search" onChange={(event) => list.set({ q: event.target.value }, { debounce: SEARCH_DEBOUNCE_MS, replace: true }) } type="search" value={list.state.q ?? ''} /> {list.state.q !== undefined && ( <button onClick={() => list.set({ q: undefined })} type="button"> Clear </button> )} <span aria-live="polite">{list.isPending ? 'Searching…' : ''}</span> </div> );}How it works
Section titled “How it works”- The input’s value is
list.state.q— the draft — so it follows every keystroke without waiting for the URL. { debounce: 300 }holds the navigation until the typing pauses;{ replace: true }keeps the searches out of the back button’s history.- Clear calls
setwithout a debounce: it goes out at once, taking any waiting keystrokes with it. articleListkeepsqexactly as typed and trims it inapply, so spaces can be typed.isPendingannounces the search while it waits and while the navigation is under way (with the Next.js App Router, until the new page has arrived).
import { useQubeeList } from '@qubeejs/react';import type { RouterAdapter } from '@qubeejs/react';import { act, fireEvent, render, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { articleList } from './article-list';import { ArticleSearch } from './article-search';
/** The search box, wired to the article list and to a router the test controls. */function Harness({ router }: { router: RouterAdapter }) { return <ArticleSearch list={useQubeeList(articleList, router)} />;}
/** Render the box at /articles, with the given query string (none by default). */function renderSearch(search = '') { const navigate = vi.fn<RouterAdapter['navigate']>();
render(<Harness router={{ navigate, pathname: '/articles', search }} />);
return { input: screen.getByRole<HTMLInputElement>('searchbox', { name: 'Search articles' }), navigate, };}
describe('ArticleSearch', () => { beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('should keep the space the user just typed', () => { const { input } = renderSearch();
fireEvent.change(input, { target: { value: 'hello ' } });
expect(input.value).toBe('hello '); });
it('should navigate once, 300 ms after the last keystroke', () => { const { input, navigate } = renderSearch();
fireEvent.change(input, { target: { value: 're' } }); fireEvent.change(input, { target: { value: 'react' } });
expect(input.value).toBe('react'); expect(navigate).not.toHaveBeenCalled();
act(() => { vi.advanceTimersByTime(300); });
expect(navigate).toHaveBeenCalledTimes(1); expect(navigate).toHaveBeenCalledWith('/articles?q=react', { replace: true }); });
it('should clear at once, taking the waiting change with it', () => { const { input, navigate } = renderSearch('?q=old');
fireEvent.change(input, { target: { value: 'react' } }); fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
expect(navigate).toHaveBeenCalledTimes(1); expect(navigate).toHaveBeenCalledWith('/articles', { replace: false }); expect(input.value).toBe(''); });});They need nothing but a fake router: navigate is a spy, and pathname and search are fixed. More
in Testing.