Skip to content

Commit 83193de

Browse files
Improve documentation for cache functions (#654)
Co-authored-by: Sarah <[email protected]> Co-authored-by: Sarah Gerrard <[email protected]>
1 parent 6865828 commit 83193de

File tree

1 file changed

+71
-29
lines changed
  • src/routes/solid-router/reference/data-apis

1 file changed

+71
-29
lines changed

Diff for: src/routes/solid-router/reference/data-apis/cache.mdx

+71-29
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,35 @@
22
title: cache
33
---
44

5-
Cache is used to prevent duplicate fetching and to trigger handle refetching.
6-
It takes a function and returns the same function.
5+
`cache` is a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function) designed to create a new function with the same signature as the function passed to it.
6+
When this newly created function is called for the first time with a specific set of arguments, the original function is run, and its return value is stored in a cache and returned to the caller of the created function.
7+
The next time the created function is called with the same arguments (as long as the cache is still valid), it will return the cached value instead of re-executing the original function.
78

8-
```jsx
9-
const getUser = cache((id) => {
10-
return (await fetch(`/api/users${id}`)).json()
11-
}, "users") // used as cache key + serialized arguments
12-
```
9+
10+
<Callout>
11+
`cache` can be defined anywhere and then used inside your components with [`createAsync`](/solid-router/reference/data-apis/create-async).
1312

14-
It is expected that the arguments to the cache function are serializable.
13+
However, using `cache` directly in [`createResource`](/reference/basic-reactivity/create-resource) will not work since the fetcher is not reactive and will not invalidate properly.
1514

16-
This cache accomplishes the following:
15+
</Callout>
1716

18-
1. Deduping on the server for the lifetime of the request.
19-
2. Preloading the cache in the browser - this lasts 10 seconds.
20-
When a route is preloaded on hover or when load is called when entering a route it will make sure to dedupe calls.
21-
3. A reactive refetch mechanism based on key.
22-
This prevents routes that are not new from retriggering on action revalidation.
23-
4. Serve as a back/forward cache for browser navigation for up to 5 minutes.
24-
Any user based navigation or link click bypasses it.
25-
Upon revalidation or new fetch the cache is updated.
17+
## Usage
18+
19+
```js
20+
const getUser = cache(
21+
(id, options = {}) => fetch(`/api/users/${id}?summary=${options.summary || false}`).then(r => r.json()),
22+
"usersById"
23+
);
24+
25+
getUser(123); // Causes a GET request to /api/users/123?summary=false
26+
getUser(123); // Does not cause a GET request
27+
getUser(123, { summary: true }); // Causes a GET request to /api/users/123?summary=true
28+
setTimeout(() => getUser(123, { summary: true }), 999000); // Eventually causes another GET request to /api/users/123?summary=true
29+
```
30+
31+
### With load functions
2632

27-
Using it with a load function:
33+
Using it with a [load function](https://docs.solidjs.com/solid-router/reference/load-functions/load):
2834

2935
```js
3036
import { lazy } from "solid-js";
@@ -42,7 +48,9 @@ function loadUser({params, location}) {
4248
<Route path="/users/:id" component={User} load={loadUser} />;
4349
```
4450

45-
Inside your page component you:
51+
### Inside a route's component
52+
53+
Using it inside a route's component:
4654

4755
```jsx
4856
// pages/users/[id].js
@@ -54,22 +62,56 @@ export default function User(props) {
5462
}
5563
```
5664

57-
Cached functions provide a few useful methods for getting the key that can be used in cases with invalidation:
65+
## Cach function capabilities
66+
67+
`cache` accomplishes the following:
68+
69+
1. Deduping on the server for the lifetime of the request.
70+
2. Preloading the cache in the browser - this lasts 10 seconds.
71+
When a route is preloaded on hover or when load is called when entering a route it will make sure to dedupe calls.
72+
3. A reactive refetch mechanism based on key.
73+
This prevents routes that are not new from retriggering on action revalidation.
74+
4. Serve as a back/forward cache for browser navigation for up to 5 minutes.
75+
Any user based navigation or link click bypasses it.
76+
Upon revalidation or new fetch the cache is updated.
77+
78+
## Cache keys
79+
80+
To ensure that the cache keys are consistent and unique, arguments are deterministically serialized using JSON.stringify.
81+
Before serialization, key/value pairs in objects are sorted so that the order of properties does not affect the serialization.
82+
For instance, both `{ name: 'Ryan', awesome: true }` and `{ awesome: true, name: 'Ryan' }` will serialize to the same string so that they produce the same cache key.
83+
84+
## Return value
85+
86+
The return value is a `CachedFunction`, a function that has the same signature as the function you passed to `cache`.
87+
This cached function stores the return value using the cache key.
88+
Under most circumstances, this temporarily prevents the passed function from running with the same arguments, even if the created function is called repeatedly.
89+
90+
## Arguments
91+
92+
| argument | type | description |
93+
| -------- | ---- | ----------- |
94+
| `fn` | `(...args: any) => any` | A function whose return value you'd like to be cached. |
95+
| `name`* | string | Any arbitrary string that you'd like to use as the rest of the cache key. |
96+
97+
*Since the internal cache is shared by all the functions using `cache`, the string should be unique for each function passed to `cache`.
98+
If the same key is used with multiple functions, one function might return the cached result of the other.
99+
100+
## Methods
101+
102+
### `.key` and `.keyFor`
103+
104+
Cached functions provide `.key` and `.keyFor`, are useful when retrieving the keys used in cases involving invalidation:
58105

59106
```ts
60107
let id = 5;
61-
62108
getUser.key; // returns "users"
63109
getUser.keyFor(id); // returns "users[5]"
64110
```
65111

112+
### `revalidate`
113+
66114
The cache can be revalidated using the `revalidate` method or the `revalidate` keys that are set on the response from the actions.
67-
If the whole key is passed, it will invalidate all entries for the cache (ie. `users` in the example above).
115+
If the entire key is passed, it will invalidate all entries for the cache (ie. `users` in the example above).
68116
If only a single entry needs to be invalidated, `keyFor` is provided.
69-
70-
<Callout>
71-
`cache` can be defined anywhere and then used inside your components with [`createAsync`](/solid-router/reference/data-apis/create-async).
72-
73-
However, using `cache` directly in [`createResource`](/reference/basic-reactivity/create-resource) will not work since the fetcher is not reactive and will not invalidate properly.
74-
75-
</Callout>
117+
To revalidate everything in the cache, pass `undefined` as the key.

0 commit comments

Comments
 (0)