[Tips] How to persist a value with localStorage/AsyncStorage
See original GitHub issueIt’s not supported by the lib itself, but here’s an idea how to persist data.
const strAtom = atom(localStorage.getItem('myKey') ?? 'foo')
const strAtomWithPersistence = atom(
get => get(strAtom),
(get, set, newStr) => {
set(strAtom, newStr)
localStorage.setItem('myKey', newStr)
},
)
or
const strAtom = atom('foo')
const persistStrAtom = atom(
null,
(get, set, action) => {
if (action.type === 'init') {
const str = localStorage.getItem('myKey')
if (str !== null) {
set(strAtom, str)
}
} else if (action.type === 'set') {
set(strAtom, action.str)
localStorage.setItem('myKey', str)
}
},
)
Issue Analytics
- State:
- Created 3 years ago
- Reactions:8
- Comments:18 (11 by maintainers)
Top Results From Across the Web
A guide to React Native's AsyncStorage - LogRocket Blog
AsyncStorage just like the localStorage in the web, persists data using key-value pairs just like localStorage .
Read more >Saving objects using AsyncStorage | by Luis Bajaña - Medium
So, I'll need to handle this as an array, since it is not supported by the API I'll have to use some parsing...
Read more >How to store value in LocalStorage in React Native
There are several options to do such thing. For most basic things you can use AsyncStorage from react-native, but there are other options, ......
Read more >AsyncStorage - React Native
AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of ...
Read more >React Native Async Storage (persist) Patterns for beginners
Storing values in the local machine, accessible the next time the user runs is a handy feature. On the web, we have the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
Top Related Hashnode Post
No results found
Agreed. We’d eventually move them to readme or a upcoming website.
Can you just asign the atom to itself instead of creating 2 different atoms? Is that “correct” ? thanks 😃
for example smth like this: