In a previous post, I created a custom Table component to display many items coming from the backend. I also created a pagination store and a pagination component to manage the pagination and the sort order.
Let’s continue in this article with the two features that remain for an interactive table: the filters and the search box.
Filtering
Once the pagination is done on the server, filtering on the client isn’t an option anymore. The browser only holds one page. If I filter the 20 users of page 3 by role, I only get the admins that happen to be on page 3. The pagination still says there are 50 pages, and the user has no idea the other admins exist.
So the filters go to the backend together with the page and the sort order. And as the PaginationStore already decides what the backend receives, the filters go in the same store. One object builds the whole query.
There is one rule to follow: changing a filter sends the user back to the first page. If I’m on page 12 of all the users and I select only the admins, I would request page 12 of a list that may have 2 pages.
Here is the updated store.
import { makeAutoObservable } from 'mobx';export class PaginationStore { currentPage = 0; maxPages = 1; sortByColumnIndex: number | null = null; sortOrder = 'asc'; filters: Record<string, string> = {}; searchQuery = ''; constructor() { makeAutoObservable(this); } get queryString() { const params = new URLSearchParams({ page: String(this.currentPage), sortOrder: this.sortOrder, }); if (this.sortByColumnIndex !== null) { params.set('sortColumn', String(this.sortByColumnIndex)); } if (this.searchQuery) { params.set('q', this.searchQuery); } Object.entries(this.filters) .filter(([, value]) => value) .forEach(([key, value]) => params.set(key, value)); return params.toString(); } setMaxPages(max: number) { this.maxPages = max; if (this.currentPage > max) { this.currentPage = max; } } nextPage() { this.currentPage++; } prevPage() { this.currentPage = Math.max(0, this.currentPage - 1); } setPage(page: number) { this.currentPage = Math.max(0, Math.min(page, this.maxPages)); } setSort(columnIndex: number) { if (this.sortByColumnIndex === columnIndex) { this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'; } else { this.sortByColumnIndex = columnIndex; this.sortOrder = 'asc'; } this.currentPage = 0; } setFilter(key: string, value: string) { this.filters = { ...this.filters, [key]: value }; this.currentPage = 0; } clearFilters() { this.filters = {}; this.currentPage = 0; } setSearchQuery(query: string) { if (query === this.searchQuery) { return; } this.searchQuery = query; this.currentPage = 0; } reset() { this.currentPage = 0; this.maxPages = 1; this.sortByColumnIndex = null; this.sortOrder = 'asc'; this.filters = {}; this.searchQuery = ''; }}
The queryString getter is a MobX computed value. It’s recalculated only when the page, the sort, the search or the filters change. In Part 1, the fetch built the URL by hand and depended on three fields of the store. Now it depends on a single string.
An empty filter stays in the map and is skipped when building the query. This way, the “All” option of a select is just an empty string, and I don’t need a separate method to remove a filter.
Now the component. I don’t want a component per filter, so I’ve created a generic select which only knows the store and the field to filter.
import { observer } from 'mobx-react-lite';import { PaginationStore } from 'src/stores/PaginationStore';type FilterSelectProps = { store: PaginationStore; field: string; label: string; options: string[];};const FilterSelect = observer(({ store, field, label, options }: FilterSelectProps) => ( <label> {label} <select value={store.filters[field] ?? ''} onChange={(event) => store.setFilter(field, event.target.value)} > <option value="">All</option> {options.map((option) => ( <option key={option} value={option}>{option}</option> ))} </select> </label>));export default FilterSelect;
The same component works for the role, the status or the country column. It’s the same reason I passed the store as a parameter of the Pagination component: easier to test, and it works with several tables on the same page.
Auto-Complete Search
The search box is where a naive implementation hurts the backend the most. With one request per keystroke, typing “sergio” sends six requests. And the responses can come back in any order. If the response for “ser” arrives after the one for “sergio”, the table displays the wrong results while the input shows the right text.
I need two things to fix that. A debounce on the input, so the request is sent only when the user stops typing. And an AbortController on the fetch, so a slow response from an old query never overwrites a recent one.
Let’s start with the search box.
import { useEffect, useState } from 'react';import { PaginationStore } from 'src/stores/PaginationStore';const DEBOUNCE_DELAY_MS = 300;const MIN_QUERY_LENGTH = 2;type SearchBoxProps = { store: PaginationStore; placeholder?: string;};const SearchBox = ({ store, placeholder }: SearchBoxProps) => { const [value, setValue] = useState(store.searchQuery); useEffect(() => { const trimmed = value.trim(); const query = trimmed.length >= MIN_QUERY_LENGTH ? trimmed : ''; const timeoutId = setTimeout(() => store.setSearchQuery(query), DEBOUNCE_DELAY_MS); return () => clearTimeout(timeoutId); }, [value, store]); return ( <input type="search" value={value} placeholder={placeholder} onChange={(event) => setValue(event.target.value)} /> );};export default SearchBox;
The input has its own local state. It updates at each keystroke, and the store only receives the value after 300 ms without typing. Each new keystroke clears the previous timeout, so typing “sergio” quickly ends up in a single request.
Below 2 characters, I send an empty query. Searching for “s” matches almost every row and costs a full scan for nothing.
This is also why setSearchQuery returns early when the query didn’t change. The effect runs when the component mounts. Without that check, the user would go to page 4, and 300 ms later the search box would send an empty query and reset the table to page 0.
Now let’s put this all together in the UserList component.
import React, { useEffect, useState, useMemo } from 'react';import { observer } from 'mobx-react-lite';import { PaginationStore } from 'src/stores/PaginationStore';import Table from './Table';import Pagination from './Pagination';import FilterSelect from './FilterSelect';import SearchBox from './SearchBox';interface User { id: number; name: string; email: string; role: string;}const ROLES = ['admin', 'editor', 'viewer'];const columnConsumers = [ (user: User) => user.name, (user: User) => user.email, (user: User) => user.role,];const UserList: React.FC = observer(() => { const [users, setUsers] = useState<User[]>([]); const [loading, setLoading] = useState(false); const paginationStore = useMemo(() => new PaginationStore(), []); const { queryString } = paginationStore; useEffect(() => { const controller = new AbortController(); const fetchData = async () => { setLoading(true); try { const response = await fetch(`/api/users?${queryString}`, { signal: controller.signal, }); const data = await response.json(); setUsers(data.items); paginationStore.setMaxPages(data.totalPages); } catch (error) { if (!controller.signal.aborted) { console.error(error); } } finally { if (!controller.signal.aborted) { setLoading(false); } } }; fetchData(); return () => controller.abort(); }, [queryString, paginationStore]); return ( <div> <div className="table-toolbar"> <SearchBox store={paginationStore} placeholder="Search by name or email" /> <FilterSelect store={paginationStore} field="role" label="Role" options={ROLES} /> </div> {loading ? ( <p>Loading...</p> ) : ( <> <Table items={users} columnNames={['Name', 'Email', 'Role']} columnConsumers={columnConsumers} paginationStore={paginationStore} onRequestEdit={(id) => console.log('Edit', id)} onRequestDelete={(id) => console.log('Delete', id)} rowUrl="/users/" /> {paginationStore.maxPages > 1 && ( <Pagination store={paginationStore} /> )} </> )} </div> );});export default UserList;
Each time queryString changes, React runs the cleanup of the previous effect before the new one. The cleanup aborts the pending request, so only the response of the last query reaches setUsers. The aborted fetch throws an error, which I ignore, and it doesn’t touch the loading flag either, since the new request already set it.
Watch where the search box is. In Part 1, the whole table was replaced by “Loading…” during the fetch. If the search box were inside that block, every request would unmount the input, and the user would lose the focus in the middle of a word. The toolbar stays outside the loading condition.
I’ve also moved columnConsumers outside of the component. It doesn’t depend on anything inside, so there is no reason to recreate the array at each render.
On the Backend Side
The frontend now sends something like /api/users?page=0&sortOrder=asc&q=sergio&role=admin. The backend must handle the filters and the search in the same query as the pagination, and return the total of pages for the filtered result, not for the whole table.
Be careful with the search. A LIKE '%sergio%' can’t use a regular B-tree index, so on a big table each search is a full scan. A full-text index (tsvector in PostgreSQL, FULLTEXT in MySQL) or a trigram index with pg_trgm handles it much better. I’ve described other techniques for the backend in this article.
With this, the browser holds a single page whatever the size of the table. The page, the sort order, the filters and the search are all built by the same store into one query string, and the backend does the filtering with its indexes.


Leave a Reply