Hello im new to react native and i want to save datas in my mobile locale storage, I use async storage for storing the data, the data that im sending is an object and i want to store it in an array. So the data that i have been created will store permanently in an Array.
This is the data that i sent
const createMessage = () => {
const formData = {
judul,
deskripsi,
startDate,
endDate,
type
};
storeMessage(formData)
};
this is the storage and how to get the data
export const storeMessage = async (value) => {
try {
const jsonValue = JSON.stringify(value)
await AsyncStorage.multiSet('MESSAGE_DATA', [jsonValue])
} catch (e) {
// saving error
}
}
export const getMessage = async () => {
try {
const jsonValue = await AsyncStorage.getItem('MESSAGE_DATA')
jsonValue != null ? JSON.parse(jsonValue) : null;
console.log('value', jsonValue)
return jsonValue
} catch (e) {
// error reading value
}
}
And the getMessage return this data {"_U": 0, "_V": 0, "_W": null, "_X": null}
How should I call my storage data
CodePudding user response:
export const storeMessage = async (value) => {
try {
const jsonValue = JSON.stringify([value])
await AsyncStorage.multiSet('MESSAGE_DATA', jsonValue)
} catch (e) {
// saving error
}
}
export const getMessage = async () => {
try {
const jsonValue = await AsyncStorage.getItem('MESSAGE_DATA')
jsonValue != null ? JSON.parse(jsonValue) : null;
console.log('value', jsonValue)
return jsonValue
} catch (e) {
// error reading value
}
}
this is the way to do it and the message you getting is because your function is async so you need to use the await for it to return data call it like this
const data = await getMessage();
CodePudding user response:
multiset and setItem are different.
You are using multiset getItem, which means you are not getting the correct pair.
MultiSet and MultiGet
multi set a key pair values, specified by an array of values.
const firstPair = ["@MyApp_user", "value_1"]
const secondPair = ["@MyApp_key", "value_2"]
await AsyncStorage.multiSet([firstPair, secondPair])
If you use multiset then you need to use multiget to get the value.
const values = await AsyncStorage.multiGet(['@MyApp_user', '@MyApp_key'])
setItem and getItem
If you want to use getItem,then it must be used with setItem, together with JSON.stringify and JSON.parse
setItem
await AsyncStorage.multiSet('MESSAGE_DATA', JSON.stringify(value))
getItem
let jsonValue = await AsyncStorage.getItem('MESSAGE_DATA')
jsonValue = jsonValue !== null ? JSON.parse(jsonValue) : null;