Skip to content

Commit

Permalink
Introducing cacheLifetime and distinction between revalidation and …
Browse files Browse the repository at this point in the history
…invalidation
  • Loading branch information
dkzlv committed Apr 3, 2024
1 parent 93421af commit f564fed
Show file tree
Hide file tree
Showing 4 changed files with 304 additions and 155 deletions.
80 changes: 41 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,12 @@

A tiny data fetcher for [Nano Stores](https://github.com/nanostores/nanostores).

- **Small**. 1.62 Kb (minified and gzipped).
- **Familiar DX**. If you've used [`swr`](https://swr.vercel.app/) or
[`react-query`](https://react-query-v3.tanstack.com/), you'll get the same treatment,
but for 10-20% of the size.
- **Built-in cache**. `stale-while-revalidate` caching from
[HTTP RFC 5861](https://tools.ietf.org/html/rfc5861). User rarely sees unnecessary
loaders or stale data.
- **Revalidate cache**. Automaticallty revalidate on interval, refocus, network
recovery. Or just revalidate it manually.
- **Nano Stores first**. Finally, fetching logic *outside* of components. Plays nicely
with [store events](https://github.com/nanostores/nanostores#store-events),
[computed stores](https://github.com/nanostores/nanostores#computed-stores),
[router](https://github.com/nanostores/router), and the rest.
- **Transport agnostic**. Use GraphQL, REST codegen, plain fetch or anything,
that returns Promises.
- **Small**. 1.93 Kb (minified and gzipped).
- **Familiar DX**. If you've used [`swr`](https://swr.vercel.app/) or [`react-query`](https://react-query-v3.tanstack.com/), you'll get the same treatment, but for 10-20% of the size.
- **Built-in cache**. `stale-while-revalidate` caching from [HTTP RFC 5861](https://tools.ietf.org/html/rfc5861). User rarely sees unnecessary loaders or stale data.
- **Revalidate cache**. Automaticallty revalidate on interval, refocus, network recovery. Or just revalidate it manually.
- **Nano Stores first**. Finally, fetching logic *outside* of components. Plays nicely with [store events](https://github.com/nanostores/nanostores#store-events), [computed stores](https://github.com/nanostores/nanostores#computed-stores), [router](https://github.com/nanostores/router), and the rest.
- **Transport agnostic**. Use GraphQL, REST codegen, plain fetch or anything, that returns Promises (Web Workers, SubtleCrypto, calls to WASM, etc.).

<a href="https://evilmartians.com/?utm_source=nanostores-query">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
Expand All @@ -34,14 +25,11 @@ npm install nanostores @nanostores/query

## Usage

See [Nano Stores docs](https://github.com/nanostores/nanostores#guide)
about using the store and subscribing to store’s changes in UI frameworks.
See [Nano Stores docs](https://github.com/nanostores/nanostores#guide) about using the store and subscribing to store’s changes in UI frameworks.

### Context

First, we define the context. It allows us to share the default fetcher
implementation between all fetcher stores, refetching settings, and allows for
simple mocking in tests and stories.
First, we define the context. It allows us to share the default fetcher implementation and general settings between all fetcher stores, and allows for simple mocking in tests and stories.

```ts
// store/fetcher.ts
Expand Down Expand Up @@ -102,17 +90,21 @@ type Options = {
// The async function that actually returns the data
fetcher?: (...keyParts: SomeKey[]) => Promise<unknown>;
// How much time should pass between running fetcher for the exact same key parts
// default = 4000 (= 4 seconds; provide all time in milliseconds)
// default = 4000 (=4 seconds; provide all time in milliseconds)
dedupeTime?: number;
// Lifetime for the stale cache. It present stale cache will be shown to a user.
// Cannot be less than `dedupeTime`.
// default = Infinity
cacheLifetime?: number;
// If we should revalidate the data when the window focuses
// default = false
refetchOnFocus?: boolean;
revalidateOnFocus?: boolean;
// If we should revalidate the data when network connection restores
// default = false
refetchOnReconnect?: boolean;
revalidateOnReconnect?: boolean;
// If we should run revalidation on an interval
// default = 0, no interval
refetchInterval?: number;
revalidateInterval?: number;
// Error handling for specific fetcher store. Will get whatever fetcher function threw
onError?: (error: any) => void;
}
Expand All @@ -128,15 +120,15 @@ Mutator basically allows for 2 main things: tell nanoquery **what data should be
It gets an object with 3 arguments:
- `data` is the data you pass to the `mutate` function;
- `invalidate` allows you to mark other keys as stale so they are refetched next time;
- `invalidate` and `revalidate`; more on them in section [How cache works](#how-cache-works)
- `getCacheUpdater` allows you to get current cache value by key and update it with
a new value. The key is also invalidated by default.
a new value. The key is also revalidated by default.
```ts
export const $addComment = createMutatorStore<Comment>(
async ({ data: comment, invalidate, getCacheUpdater }) => {
// You can either invalidate the author…
invalidate(`/api/users/${comment.authorId}`);
async ({ data: comment, revalidate, getCacheUpdater }) => {
// You can either revalidate the author…
revalidate(`/api/users/${comment.authorId}`);

// …or you can optimistically update current cache.
const [updateCache, post] = getCacheUpdater(`/api/post/${comment.postId}`);
Expand Down Expand Up @@ -193,15 +185,10 @@ You can also access the mutator function via `$addComment.mutate`—the function
// store/fetcher.ts
import { nanoquery } from '@nanostores/query';

export const [,, { invalidateKeys, mutateCache }] = nanoquery();
export const [,, { invalidateKeys, revalidateKeys, mutateCache }] = nanoquery();
```

`invalidateKeys` does 2 things:

1. nukes all cache for the specified keys;
2. asks all the fetcher stores that used those keys to refresh data immediately, if they have active subscribers.

It accepts one argument—the keys—in 3 different forms, that we call _key selector_.
Both `invalidateKeys` and `revalidateKeys` accept one argument—the keys—in 3 different forms, that we call _key selector_. More on them in section [How cache works](#how-cache-works)

```ts
// Single key
Expand All @@ -228,6 +215,21 @@ Keep in mind: we're talking about the serialized singular form of keys here. You

## Recipes

### How cache works

All of this is based on [`stale-while-revalidate`](https://tools.ietf.org/html/rfc5861) methodology. The goal is simple:

1. user visits `page 1` that fetches `/api/data/1`;
2. user visits `page 2` that fetches `/api/data/2`;
3. almost immediately user goes back to `page 1`. Instead of showing a spinner and loading data once again, we fetch it from cache.

So, using this example, let's try to explain different cache-related settings the library has:

- `dedupeTime` is the time that user needs to spend on `page 2` before going back for the library to trigger fetch function once again.
- `cacheLifetime` is the maximum possible time between first visit and second visit to `page 1` after which we will stop serving stale cache to user (so they will immediately see a spinner).
- `revalidate` forces the `dedupeTime` for this key to be 0, meaning, the very next time anything can trigger fetch (e.g., `refetchOnInterval`), it will call fetch function. If you were on the page during revalidation, you'd see cached value during loading.
- `invalidate` kills this cache value entirely—it's as if you never were on this page. If you were on the page during invalidation, you'd see a spinner immediately.

### Local state and Pagination

All examples above use module-scoped stores, therefore they can only have a single
Expand Down Expand Up @@ -258,23 +260,23 @@ We've already walked through all the primitives needed for refetching and mutati

For these cases we have 3 additional things on fetcher stores:

1. `fetcherStore.invalidate`. It's a function that invalidates current key for the fetcher. Doesn't accept any arguments.
1. `fetcherStore.invalidate` and `fetcherStore.revalidate`
2. `fetcherStore.mutate`. It's a function that mutates current key for the fetcher. Accepts the new value.
3. `fetcherStore.key`. Well, it holds current key in serialized form (as a string).

Typically, those 3 are more than enough to make all look very good.

### Dependencies, but not in keys

Let's say, you have a dependency for your fetcher, but you don't wish for it to be in your fetcher keys. For example, this could be your `refreshToken`—that would be a hassle to put it _everywhere_, but you need it, because once you change your user, you don't want to have stale cache from the previous user.
Let's say, you have a dependency for your fetcher, but you don't want it to be in your fetcher keys. For example, this could be your `userId`—that would be a hassle to put it _everywhere_, but you need it, because once you change your user, you don't want to have stale cache from the previous user.

The idea here is to wipe the cache manually. For something as big as a new refresh token you can go and do a simple "wipe everything you find":

```ts
onSet($refreshToken, () => invalidateKeys(() => true))
```

But if your store is somehow dependant on other store, but it shouldn't be reflected in the key, you should do the same, but more targetly:
If your store is somehow dependant on other store, but it shouldn't be reflected in the key, you should do the same, but more targetly:

```ts
onSet($someOutsideFactor, $specificStore.invalidate)
Expand Down
Loading

0 comments on commit f564fed

Please sign in to comment.