I am trying to append an Object to an existing array of objects in AsyncStorage, however not being successful. Any help is appreciated!
Current code:
const [storageItems, setStorageItems] = useState([]);
const handleHabitCreation = async () => {
setLoading(true);
const newHabit = {
name: name,
color: updatedColor,
days: daysCount,
times: timesCount,
reminder: selectedDate,
description: description,
};
try {
const jsonValue = await AsyncStorage.getItem('@habit');
setStorageItems(jsonValue);
} catch (error) {
console.error(error);
}
const stringifiedHabit = JSON.stringify(newHabit);
setStorageItems([...storageItems, stringifiedHabit]);
try {
await AsyncStorage.setItem('@habit', JSON.stringify(storageItems));
setTimeout(() => {
setLoading(false);
navigation.pop(3);
}, 2500);
} catch (error) {
console.error(error);
}
};
The proplem is that you are not parsing the stringified json data. You need to parse it to perform any modification. Save the data in the state as parsed json and srtingify it just before saving it to the async storage. Try this code:
try {
const jsonValue = await AsyncStorage.getItem('@habit');
// saving parsed json
const data = JSON.parse(jsonValue)
setStorageItems(data);
} catch (error) {
console.error(error);
}
// state depends on previous state
setStorageItems((prevState) => [...prevState, newHabit]);
or to make shorter
try {
const jsonValue = await AsyncStorage.getItem('@habit');
let data = JSON.parse(jsonValue) // parse to modify
// push newHabit as well
data.push(newHabit)
setStorageItems(data);
} catch (error) {
console.error(error);
}
in both approaches, stringify the object in the end
await AsyncStorage.setItem('@habit', JSON.stringify(storageItems));