0

I try to recuperate a list from localStorage and set the table to the state like this:

const [favoritesExercices, setFavoritesExercices] = useState([]);

const retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('favoritesExercices');
    if (value !== null) {
      const ex =JSON.parse(value);
      setFavoritesExercices([...favoritesExercices, ex]);
      console.log(favoritesExercices);
    }
  } catch (e) {
    console.error(e);
  }
}

useEffect(() => {
  retrieveData();
}, []);

With debugging I can see the array in the value variable but when I do console.log to the store it is empty. Can anyone have an idea to fix this?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • 1
    The code looks fine, you just have your console.log in a spot where it isn't useful. Calling `setFavoriteExercises` does not change the local variable `favoriteExercises`, it just asks react to rerender the component. If you want to verify that the component rerenders with the new state, put the log statement in the body of the component, such as right after the line where you call `useState` – Nicholas Tower Apr 07 '23 at 12:25
  • Just to supply with a link to comment from @NicholasTower : https://react.dev/reference/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value – Roar S. Apr 07 '23 at 12:29

0 Answers0