I am facing this error when I am using JSON.parse. Below is the function. I am trying to get the values of the object in the item array for which I have to parse it first, but it is showing the error.
//function for get the data
const viewUser = async () => {
console.log('Loading');
try {
const keys = await AsyncStorage.getAllKeys()
const item = await AsyncStorage.multiGet(keys)
const data=JSON.parse(item)
} catch (error) {
console.log(error, "problem")
}
};
here is the function where I am setting the values. using math.random to get a unique key for every user.
const saveUser = async () => {
var key = Math.floor(Math.random() * 100);
console.log('Saving');
const userObject = {
firstName: firstName,
secondName: secondName,
email: email,
};
await AsyncStorage.setItem(
key,
JSON.stringify(userObject)
);
console.log('saving done!');
setFirstName('');
setSecondName('');
setEmail('');
};
CodePudding user response:
valid JSON string must have a double quote. wrap your key in a double quote using backticks
CodePudding user response:
The return values from AsyncStorage.multiGet(keys)
is not a stringified JSON but an array of tuples. To get the values you need to do the following:
const viewUser = async () => {
console.log('Loading');
try {
const keys = await AsyncStorage.getAllKeys()
const items = await AsyncStorage.multiGet(keys)
// items is an array of tuples with first value as the key and second as the value
let data = {}
items.forEach(item => {
data[item[0]] = item[1]
})
} catch (error) {
console.log(error, "problem")
}
};