deno.land / x / jotai@v1.8.4 / docs / guides / persistence.mdx

persistence.mdx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
---title: Persistencedescription: How to persist atomsnav: 3.03---
Jotai has an [atomWithStorage function in the utils bundle](../api/utils.mdx#atom-with-storage) for persistence that supports persisting state in `sessionStorage`, `localStorage`, `AsyncStorage`, or the URL hash.
There are also several alternate implementations here:
## A simple pattern with localStorage
```jsconst strAtom = atom(localStorage.getItem('myKey') ?? 'foo')
const strAtomWithPersistence = atom( (get) => get(strAtom), (get, set, newStr) => { set(strAtom, newStr) localStorage.setItem('myKey', newStr) })```
## A helper function with localStorage and JSON parse
```jsconst atomWithLocalStorage = (key, initialValue) => { const getInitialValue = () => { const item = localStorage.getItem(key) if (item !== null) { return JSON.parse(item) } return initialValue } const baseAtom = atom(getInitialValue()) const derivedAtom = atom( (get) => get(baseAtom), (get, set, update) => { const nextValue = typeof update === 'function' ? update(get(baseAtom)) : update set(baseAtom, nextValue) localStorage.setItem(key, JSON.stringify(nextValue)) } ) return derivedAtom}```
(Error handling should be added.)
## A helper function with AsyncStorage and JSON parse
This requires [onMount](../api/core.mdx#on-mount).
```jsconst atomWithAsyncStorage = (key, initialValue) => { const baseAtom = atom(initialValue) baseAtom.onMount = (setValue) => { ;(async () => { const item = await AsyncStorage.getItem(key) setValue(JSON.parse(item)) })() } const derivedAtom = atom( (get) => get(baseAtom), (get, set, update) => { const nextValue = typeof update === 'function' ? update(get(baseAtom)) : update set(baseAtom, nextValue) AsyncStorage.setItem(key, JSON.stringify(nextValue)) } ) return derivedAtom}```
Don't forget to check out the [Async documentation](./async) for more details on how to use async atoms.
### Usage in Async actions
When using an asynchronous storage, the reading of the created atoms are asynchronous too. That comes with some limitations. Before `useAtom` has been called at least once, the value is not set.This can cause an issue, for example, if you want to retrieve the value of your stored atom in an async action (write-only atom).
Let's use the [atomWithStorage function in the utils bundle](../api/utils.mdx#atom-with-storage) for the examples, so that we have more options available.
```jsimport { atomWithStorage, createJSONStorage } from 'jotai/utils'
const storage = createJSONStorage(() => AsyncStorage)const userId = atomWithStorage('user-id-key', null, storage)const userInfo = atom({})const fetchUserInfo = atom(null, async (get, set, payload: any) => { const id = get(userId) // This throws an error if "userId" is not loaded yet const info = await fetch('https://jotai.org/users/' + id) set(userInfo, info)})```
We want to make sure the action will never fail. As always with asynchronous flow in Jotai, we have 2 options: with or without **Suspense**.
#### With Suspense
You may want to preload atoms at root level of your app directly:
```jsconst Preloader = () => { useAtomValue(userId) // Trigger the "onMount" function that will load the data from the store return null}```
```jsxconst Root = () => { return ( <Suspense fallback={<Text>Hydrating...<Text>}> <Preloader /> {/* Wait for atoms to preload */} <App /> {/* Rest of your app */} </Suspense> )}```
#### Without Suspense
```js// We add the "delayInit: true" option to tell jotai not to use Suspenseconst storage = { ...createJSONStorage(() => AsyncStorage), delayInit: true }const userId = atomWithStorage('user-id-key', null, storage)const userInfo = atom({})const fetchUserInfo = atom(null, async (get, set, payload) => { let id = get(userId) if (id === null) { // We make sure to preload if no value has yet been loaded id = await AsyncStorage.getItem('user-id-key') } const info = await fetch('https://jotai.org/users/' + id) set(userInfo, info)})```
But always remember jotai is un-opinionated and your workflow may not need preloading at all.
---
## Example with sessionStorage
Same as AsyncStorage, just use `atomWithStorage` util and override the default storage with the `sessionStorage`
```jsimport { atomWithStorage, createJSONStorage } from 'jotai/utils'
const storage = createJSONStorage(() => sessionStorage)const someAtom = atomWithStorage('some-key', someInitialValue, storage)```
## A serialize atom pattern
```tsxconst serializeAtom = atom< null, | { type: 'serialize'; callback: (value: string) => void } | { type: 'deserialize'; value: string }>(null, (get, set, action) => { if (action.type === 'serialize') { const obj = { todos: get(todosAtom).map(get), } action.callback(JSON.stringify(obj)) } else if (action.type === 'deserialize') { const obj = JSON.parse(action.value) // needs error handling and type checking set( todosAtom, obj.todos.map((todo: Todo) => atom(todo)) ) }})
const Persist = () => { const [, dispatch] = useAtom(serializeAtom) const save = () => { dispatch({ type: 'serialize', callback: (value) => { localStorage.setItem('serializedTodos', value) }, }) } const load = () => { const value = localStorage.getItem('serializedTodos') if (value) { dispatch({ type: 'deserialize', value }) } } return ( <div> <button onClick={save}>Save to localStorage</button> <button onClick={load}>Load from localStorage</button> </div> )}```
### Examples
<CodeSandbox id="ijyxm" />## A pattern with atomFamily
```tsxconst serializeAtom = atom< null, | { type: 'serialize'; callback: (value: string) => void } | { type: 'deserialize'; value: string }>(null, (get, set, action) => { if (action.type === 'serialize') { const todos = get(todosAtom) const todoMap: Record<string, { title: string; completed: boolean }> = {} todos.forEach((id) => { todoMap[id] = get(todoAtomFamily({ id })) }) const obj = { todos, todoMap, filter: get(filterAtom), } action.callback(JSON.stringify(obj)) } else if (action.type === 'deserialize') { const obj = JSON.parse(action.value) // needs error handling and type checking set(filterAtom, obj.filter) obj.todos.forEach((id: string) => { const todo = obj.todoMap[id] set(todoAtomFamily({ id, ...todo }), todo) }) set(todosAtom, obj.todos) }})
const Persist = () => { const [, dispatch] = useAtom(serializeAtom) const save = () => { dispatch({ type: 'serialize', callback: (value) => { localStorage.setItem('serializedTodos', value) }, }) } const load = () => { const value = localStorage.getItem('serializedTodos') if (value) { dispatch({ type: 'deserialize', value }) } } return ( <div> <button onClick={save}>Save to localStorage</button> <button onClick={load}>Load from localStorage</button> </div> )}```
### Examples
<CodeSandbox id="eilkg" />
jotai

Version Info

Tagged at
a year ago