Is there any way to store values other than strings with AsyncStorage? I want to store simple boolean values for example.
AsyncStorage.setItem(\'key\', \'ok\
I always use/create a wrapper modulee around AsyncStorage, utilising JSON.parse & JSON.stringify on the data coming in and out.
This way you remove the need to have you JSON.parse & JSON.stringify calls inside your business logic. This keeps the code a bit nicer on the eye.
Something like
import AsyncStorage from "@react-native-community/async-storage";
export const Storage {
getItem: async (key) => {
try {
let result = await AsyncStorage.getItem(key);
return JSON.parse(result);
}
catch (e) {
throw e;
}
},
setItem: async (key, value) => {
try {
const item = JSON.stringify(value);
return await AsyncStorage.setItem(key, item);
} catch (e) {
throw e;
}
}
}
// usage
async function usage () {
const isLeeCool = true;
const someObject = { name: "Dave" };
const someArray = ["Lee", "Is", "Cool."];
try {
// Note Async storage has a method where you can set multiple values,
// that'd be a better bet here (adding it to the wrapper).
await Storage.setItem("leeIsCool", leeIsCool);
await Storage.setItem("someObject", someObject);
await Storage.setItem("someArray", someArray);
} catch (e) {}
// Some point later that day...
try {
console.log(await Storage.getItem("leeIsCool"));
console.log(await Storage.getItem("someObject"));
console.log(await Storage.getItem("someArray"));
} catch (e) {}
}