atomWithStorage in React Native trouble using AsyncStorage
See original GitHub issueHi, not sure if I’ve got something configured wrong or what but it seems like setting up the atomWithStorage
function is not working great for me in React Native. I started by defining a simple atom with storage and a default state:
export const appSettingsAtom = atomWithStorage<AppSettings>('@appSettings', {
servers: [],
});
but whenever I try to set it I get this error:
After scanning through the code for atomWithStorage
it looks like there is no AsyncStorage implementation at all currently. Turns out I didn’t read the docs closely enough and had assumed that AsyncStorage support was built-in, but I guess it’s not. Doesn’t seem like I can pass AsyncStorage
directly as the third param to atomWithStorage
since it’s not type compatible, so I tried to implement my own Storage object (which I would prefer to do anyway so I can handle my own logging later):
export async function getItem(key: string): Promise<any | null> {
try {
const item = await AsyncStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (e) {
console.error(`getItem error (key: ${key})`, e);
return null;
}
}
export async function setItem(key: string, item: any): Promise<void> {
try {
await AsyncStorage.setItem(key, JSON.stringify(item));
} catch (e) {
console.error(`setItem error (key: ${key})`, e);
}
}
export const atomStore = {
getItem,
setItem,
delayInit: true,
}
…but now I get an error about the value of the atom being null:
Ok, maybe that’s because my getItem
function can return null if the key doesn’t exist, but that’s weird since that’s the default behavior for AsyncStorage. Alright, so now I re-implement getItem
to also return the default value:
import { getItem, setItem } from '../storage/asyncstorage';
export const appSettingsAtom = atomWithStorage<AppSettings>('@appSettings', {
servers: [],
}, {
getItem: async () => {
const item = await getItem('@appSettings');
return item || { servers: [] };
},
setItem: setItem,
delayInit: true,
});
And now it finally seems to work, but I have to tell it about my key and default value multiple times, which doesn’t feel great. I could wrap this up in another utility function on my end that provides these things, but I guess I’m left wondering is this the intended workflow here with AsyncStorage or am I missing a built-in utility somewhere that simplifies this?
Issue Analytics
- State:
- Created 2 years ago
- Comments:9 (5 by maintainers)
Seems good to me, maybe exporting the
Storage<T>
type then is something that will be better for a more fully-fledgedjotai-storage
package like you mentioned in the future.Check the latest code in the PR.
Now, it would allow you this:
Please git it a try.