Eric Bower
·
26 Aug 24
caching.md
1---
2title: Caching
3description: How to store data in starfx
4---
5
6There are two primary ways to store data in `starfx`:
7
8- Manual
9- Automatic
10
11# Manual
12
13You have full control over how data is stored in your app, however, the cost is
14managing it.
15
16For anything beyond the simplest of apps, actively managing your state is going
17to promote a more robust and managable codebase. When you are performing CRUD
18operations and want to store those records in a database table that is strongly
19typed, you probably want manually managed.
20
21The good news this is really easy in `starfx` because we can leverage
22[schemas](/schema) to do most of the heavy lifting.
23
24# Automatic
25
26This one is simpler to setup, easy for it to "just work" and is more like
27`react-query`.
28
29When using an endpoint, this method simply stores whatever is put inside
30`ctx.json`. Then you can access that data via `useCache`.
31
32```tsx
33import { createApi } from "starfx";
34import { useCache } from "starfx/react";
35
36const api = createApi();
37const fetchUsers = api.get("/users", api.cache());
38
39function App() {
40 const { data = [] } = useCache(fetchUsers());
41 return <div>{data.map((user) => <div>{user.name}</div>)}</div>;
42}
43```
44
45`api.cache()` opts into automatic caching. This is really just an alias for:
46
47```ts
48function*(ctx, next) {
49 ctx.cache = true;
50 yield* next();
51}
52```
53
54The state slice for `cache` is simple, every thunk action has
55[special properties](/thunks#anatomy-of-an-action) of which one is a `key` field
56that is a hash of the entire user-defined action payload:
57
58```js
59{
60 [action.payload.key]: {},
61}
62```
63
64# `timer` supervisor
65
66This supervisor can help us with how often we refetch data. This will help us
67call the same endpoint many times but only fetching the data on an interval.
68
69[Read more about it in Supervisors](/supervisors#timer)
70
71This, cominbed with [Automatic caching](#automatic) provides us with the
72fundamental features built into `react-query`.