examples/react/contacts-tanstack-router
| Name | Last commit message | Last commit date |
|---|---|---|
| .. | ||
README.md
TanStack React Query Contacts Example (TanStack Router)#
A contacts app whose router loaders read from the query cache and whose mutations invalidate it.
Built with TanStack Router.
How it works#
src/services/contacts/queries.tsdefinescontactsQueries.list(q)andcontactsQueries.detail(id)withqueryOptions, andcontactsMutations.create(),update(), anddelete()withmutationOptions. The detailqueryFnthrows TanStack Router'snotFound()when the contact does not exist.src/services/contacts/api.tsstores the contacts inlocalStoragebehind a random delay.- The loaders in
src/routes/__root.tsx(withloaderDepson theqsearch param) andsrc/routes/contacts.$contactId.route.tsxcallqueryClient.query({ ...options, staleTime: 'static' })with thequeryClientfrom the router context, which uses cached data when it exists and fetches only on a cache miss. Components read the same options withuseSuspenseQuery, After the 10-secondstaleTimeset insrc/index.tsx, the data is stale, anduseSuspenseQueryrefetches it in the background on the next trigger, such as a component mount or window focus. src/index.tsxcreates the router withdefaultPreload: 'intent', so hovering a contact link runs its loader ahead of time.src/routes/__root.tsxdebounces the search input withuseDebouncedCallbackfrom TanStack Pacer and shows a spinner whileuseIsFetching({ queryKey: contactsQueries.lists() })is greater than 0.src/routes/contacts.new.tsx,src/routes/contacts.$contactId.edit.tsx, andsrc/routes/contacts.$contactId.index.tsxrun the mutations withuseMutationand callqueryClient.invalidateQueriesafterward. The favorite button shows the pending value fromupdateContact.variableswhile the mutationisPending.
To run this example:
npm installnpm run dev