examples/react/contacts-react-router
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack React Query Contacts Example (React Router)#
A contacts app whose router loaders read from the query cache and whose mutations invalidate it.
Built with React Router.
How it works#
src/services/contacts/queries.tsdefinescontactsQueries.list(q)andcontactsQueries.detail(id)withqueryOptions, keyed under['contacts', 'list']and['contacts', 'detail']. The detailqueryFnthrows a 404Responsewhen the contact does not exist.src/services/contacts/api.tsstores the contacts inlocalStoragebehind a random delay.- The loaders in
src/routes/root.tsxandsrc/routes/contact.tsxawaitqueryClient.query({ ...options, staleTime: 'static' }), which uses cached data when it exists and fetches only on a cache miss. The route components then read the same options withuseSuspenseQuery, After the 10-secondstaleTimeset on theQueryClientinsrc/index.tsx, the data is stale, anduseSuspenseQueryrefetches it in the background on the next trigger, such as a component mount or window focus. src/routes/root.tsxdebounces the search input withuseDebouncedCallbackfrom TanStack Pacer and shows a spinner whileuseIsFetching({ queryKey: contactsQueries.lists() })is greater than 0.- The route actions in
src/routes/new.tsx,src/routes/edit.tsx,src/routes/contact.tsx, andsrc/routes/destroy.tsxcall the API, thenqueryClient.invalidateQueriesso the list and detail refetch.
To run this example:
npm installnpm run dev