Reputation: 47
I want to create todo list with notes with react native and redux. I have complicated logic of storing notes and todos in different places, with different statuses. How should I store all relations and all data in local storage in Android/IOS devices?
Upvotes: 3
Views: 10881
Reputation: 1409
Async Storage can only store string data, so in order to store object data you need to serialize it first. For data that can be serialized to JSON you can use JSON.stringify() when saving the data and JSON.parse() when loading the data.
import AsyncStorage from '@react-native-community/async-storage';
Storing string value
const storeData = async (value) => {
try {
await AsyncStorage.setItem('@storage_Key', value)
} catch (e) {
// saving error
}
}
Sorting Object Value
const storeData = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.setItem('@storage_Key', jsonValue)
} catch (e) {
// saving error
}
}
Reading String Value
const getData = async () => {
try {
const value = await AsyncStorage.getItem('@storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
Reading Object Value
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('@storage_Key')
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch(e) {
// error reading value
}
}
Upvotes: 5
Reputation: 1317
For that, you would use something like https://github.com/react-native-community/async-storage
However, be aware of AsyncStorage limitations such as encryption and size.
You can use it like that:
import AsyncStorage from '@react-native-community/async-storage';
export default {
setItem: async (key, value) => {
try {
await AsyncStorage.setItem(key, JSON.stringify(value));
} catch (error) {}
},
getItem: async (key) => {
try {
const item = await AsyncStorage.getItem(key);
return JSON.parse(item);
} catch (error) {}
},
removeItem: async (key) => {
try {
await AsyncStorage.removeItem(key);
} catch (error) {}
},
updateItem: async (key, value) => {
try {
const item = await AsyncStorage.getItem(key);
const result = {...JSON.parse(item), ...value};
await AsyncStorage.setItem(key, JSON.stringify(result));
} catch (error) {}
},
};
Upvotes: 0