I'm currently creating an app using react native and async storage, but there's a problem when I add the new data, it can't show it on the screen until I ctrl+s the code file, but I want that when I add the new data and go back to the screen, it must show on it. I'm new with this so if you know the problem or solutions please help me, thank u in advance.
const [data, setData] = useState();
const getData = async () => {
try {
keys = await AsyncStorage.getAllKeys();
data1 = await AsyncStorage.multiGet(keys);
obj = Object.fromEntries(data1);
Object.keys(obj).forEach(key => {
obj[key] = JSON.parse(obj[key]);
data2.push(obj[key]);
});
setData(data2);
console.log('DATA:' + data2);
return data;
} catch (error) {
console.log('Err: ', error);
}
};
useEffect(() => {
getData();
}, []);
When you are coming back this screen, useEffect is not called hence data is not fetched fom async storage.
Solution One
To call useEffect every time screen is loaded, you can use useFocusEffect
like this.
import { useFocusEffect } from '@react-navigation/native';
useFocusEffect(
React.useCallback(() => {
getData();
}, [])
);
Solution Two
another way you can call useEffect on screen load is with useIsFocused
hook,
import { useIsFocused } from "@react-navigation/native";
const isFocused = useIsFocused();
useEffect(() => {
getData();
}, [isFocused]);