I am calling a function on press of a button, to store my data in local storage using AsyncStorage
.
Below is my code to store data using AsyncStorage
const [saveData, setSaveData] = useState([]);
const _submit = async (text, photo) => {
let newItem;
newItem = {
description: text,
imageURL: photo,
};
setSaveData(prevList => {
prevList = prevList || [];
if (prevList.length < 0) {
return newItem;
} else {
return [...prevList, newItem];
}
});
setLocalItem();
};
const setLocalItem = async () => {
AsyncStorage.setItem('test2', JSON.stringify(saveData))
.then(json => console.log('success!'))
.catch(error => console.log('error!'));
};
const getLocalItem = async () => {
try {
const jsonValue = await AsyncStorage.getItem('test2');
const list = JSON.parse(jsonValue);
console.log('list: ', list);
} catch (e) {
console.log('error: ', e);
}
};
<TouchableOpacity
onPress={() => {
_submit (text, photo);
}}>
<Text>save</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
getLocalItem();
}}>
<Text>get item</Text>
</TouchableOpacity>
My data is getting stored but only after I click save
button multiple times. But in console I am getting success
even when I click save
button only once. But when I click on get item
button, I am getting null
in console if save
is clicked only once.
I am not not sure why I have to click save
multiple times to store my data.
CodePudding user response:
You're updating the state incorrectly. And the new state will be available in the next render, so setLocalItem
should be called after the state gets updated.
const [saveData, setSaveData] = useState([]);
// this effect updates the storage whenever `saveData` changes
useEffect(() => {
AsyncStorage.setItem('test2', JSON.stringify(saveData))
.then(json => console.log('success!'))
.catch(error => console.log('error!'));
}, [saveData])
const _submit = (text, photo) => {
const newItem = {
description: text,
imageURL: photo,
};
// no conditions are required here as the initial state is an array
setSaveData(prevList => [...prevList, newItem]);
};
const getLocalItem = async () => {
try {
const jsonValue = await AsyncStorage.getItem('test2');
const list = JSON.parse(jsonValue);
console.log('list: ', list);
} catch (e) {
console.log('error: ', e);
}
};