Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

simple-cache.md

202 lines5.2 KB

1---
2id: simple-cache
3title: React Location Simple Cache
4---
5​
6A simple cache created for React Location Route loaders.
7​
8- Fetch Policies
9- Stale-While-Revalidate
10- Custom Keys
11- Manual Invalidation
12​
13## Installation
14​
15```bash
16yarn add @tanstack/react-location-simple-cache
17# or
18npm i @tanstack/react-location-simple-cache
19```
20​
21## Getting Started
22​
23```tsx
24import { ReactLocation, Router } from '@tanstack/react-location'
25import { ReactLocationSimpleCache } from '@tanstack/react-location-simple-cache'
26​
27//
28​
29const routeCache = new ReactLocationSimpleCache()
30const location = new ReactLocation()
31​
32function App() {
33 return (
34 <Router
35 location={location}
36 routes={[
37 {
38 path: '/',
39 element: <Posts />,
40 loader: routeCache.createLoader(async () => ({
41 posts: await fetchPosts(),
42 })),
43 },
44 ]}
45 />
46 )
48```
49​
50## Docs
51​
52### ReactLocationSimpleCache
53​
54Use the `ReactLocationSimpleCache` class to create a new cache instance.
55​
56```tsx
57const simpleCache = new ReactLocationSimpleCache()
58```
59​
60### SimpleCacheRecord
61​
62This is the underlying shape of each record that is stored in the cache:
63​
64```tsx
65import { LoaderData, RouteMatch } from '@tanstack/react-location'
66​
67export type SimpleCacheRecord<
68 TData extends LoaderData = Record<string, unknown>,
69> = {
70 key: string
71 updatedAt: number
72 ready: boolean
73 promise?: Promise<TData>
74 data?: any
75 invalid?: boolean
76 match: RouteMatch
78```
79​
80### Fetch Policies
81​
82The caching functionality of the simple cache allows for a few different fetch policies to be used when determining if and when your loader function gets called again.
83​
84```tsx
85type FetchPolicy = 'cache-and-network' | 'cache-first' | 'network-only'
86```
87​
88- `cache-and-network`
89 - If the record is empty:
90 - navigation **suspends** while the data is fetch and cached
91 - If data is cached:
92 - Navigation is immediate
93 - If a `maxAge` **was not supplied**:
94 - The data is always refetched in the background after navigation
95 - If a `maxAge` **was supplied OR the record has been manually invalidated**:
96 - If the record has expired, the data is refetched in the background after navigation
97- `cache-first`
98 - If the record is empty:
99 - navigation **suspends** while the data is fetch and cached
100 - If data is cached:
101 - Navigation is immediate
102 - If the record has been manually marked as `invalid`, it will be refetch in the background
103 - Otherwise, the data is never refetched
104- `network-only`
105 - navigation **always suspends** while the data is fetched and cached
106​
107### `cache.createLoader`
108​
109This cache method creates a loader function for a React Location route.
110​
111```tsx
112createLoader: (
113 loader: Loader,
114 opts?: {
115 key?: (match: RouteMatch) => string
116 maxAge?: number
117 policy?: FetchPolicy
118 },
119) => Loader
120```
121​
122| Property | Description |
123| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
124| loader | The loader function you would normally pass to your router loader property |
125| key | An optional function that receives the RouteMatch object and returns a unique string used to identify the underlying record for this route. The full route pathname is used by defualt. |
126| maxAge | If using the `An optional integer of milliseconds to use as the threshold of time before the underlying data will be fetched again. |
127| policy | The [`FetchPolicy`](#fetch-policies) to be used for this loader |
128​
129```tsx
130const routes = [
131 {
132 path: ':postId',
133 element: <Post />,
134 loader: routeCache.createLoader(
135 async ({ params: { postId } }) => ({
136 post: await fetchPostById(postId),
137 }),
138 {
139 key: (match) => `posts_${match.params.postId}`,
140 },
141 ),
142 },
144```
145​
146### `cache.clearAll`
147​
148Resets the cache to its original state with no records and no data
149​
150```tsx
151type cache = {
152 removeAll(): void
154```
155​
156### `cache.clear`
157​
158Removes records from the cache by predicate function
159​
160```tsx
161type cache = {
162 remove<TLoaderData>(
163 predicateFn: (record: SimpleCacheRecord) => boolean | any,
164 ): void
166```
167​
168### `cache.filter`
169​
170Returns records by predicate function
171​
172```tsx
173type cache = {
174 filter<TLoaderData>(
175 predicateFn: (record: SimpleCacheRecord) => boolean | any,
176 ): SimpleCacheRecord<TLoaderData>
178```
179​
180### `cache.find`
181​
182Returns the first record found by predicate
183​
184```tsx
185type cache = {
186 find<TLoaderData>(
187 predicateFn: (record: SimpleCacheRecord) => boolean | any,
188 ): SimpleCacheRecord<TLoaderData>
190```
191​
192### `cache.invalidate`
193​
194Invalidates records by predicate function
195​
196```tsx
197type cache = {
198 invalidate<TLoaderData>(
199 predicateFn: (record: SimpleCacheRecord) => boolean | any,
200 ): void
202```