0
votes

I tried to get a value from AsyncStorage in my react native application, but it comes out as an empty string first.

Lets say I have 2 components, Home and About.

The About screen is where I'm getting my AsyncStorage values.

I was able to use createBottomTabNavigator to create navigation tabs at the bottom of my screen so I can toggle between Home and About.

When I press into my About screen, I tried to console log the value, but its only an empty array. If I use hooks (or useEffect) like so:

const [data, setData] = useState([])

const asyncFunctionData = async () => {
  try {
    const storageData = await AsyncStorage.getItem('key_data');
    setData(JSON.parse(storageData));
    console.log(data);
  } catch (e) {}
}

useEffect(() => {
  asyncFunctionData();
}, [data]);

The component will continuously execute for some reason, but after a couple of execution, I can finally get the value of AsyncStorage. But the issue is why is it executing multiple times and why do I get an empty array at first? I thought having [] will only execute the useEffect once or when there's an update.

Does AsyncStorage have some type of effect on the continuous execution? Also, does AsyncStorage not get any value on app load?

1

1 Answers

1
votes

Your hook doesn't depend on data that you set after getting values from AsyncStorage, also you should define async function inside useEffect

const [data, setData] = useState([])

useEffect(() => {
 const asyncFunctionData = async () => {
   try {
     const storageData = await AsyncStorage.getItem('key_data');
     setData(JSON.parse(storageData));
   } catch (e) {}
 }
 asyncFunctionData();
}, [setData]);`