Home > OS >  How do I display data received from Async Storage in React Native?
How do I display data received from Async Storage in React Native?

Time:11-23

I'm trying to display data (in the form of an array) using async storage. Console logging the data works but when I put the data in state and try to map through it to display, it wont. Any help is welcome. Thanks! Result in console log: ["team1", "team2", "team3"] before JSON.parse Array [ "team1", "team2", "team3", ] after JSON.parse

const [favoriteTeams, setFavoriteTeams] = useState([]);

const setStorage = async (team) => {
    let teams = [];
    try {
      let storedTeams = await AsyncStorage.getItem('favTeams');
      if (storedTeams !== null) {
        teams = JSON.parse(storedTeams); 
      }
      teams.push(team)
      await AsyncStorage.setItem('favTeams', JSON.stringify(teams));
    } catch (error) {
      //error
    }
};

const getStorage = async () => {
    const teams = await AsyncStorage.getItem('favTeams')
    if (teams !== null) {
        setFavoriteTeams(prevState => [...prevState, ...JSON.parse(teams)])
    }
}

useEffect(() => {
    getStorage()
}, [])

return (
    <View>
         {favoriteTeams.map((item) => {(
              <Text>{item}</Text> //console.log(item) works
          )}
       )}
    </View>
)

CodePudding user response:

Your map callback function doesn't have a return value, which is why none of the contents show up.

You should either remove the curly brackets. By removing the curly brackets your arrow function implicitly returns a single expression.

return (
  <View>
    {favoriteTeams.map((item) => (
      <Text>{item}</Text>
    ))}
  </View>
)

Alternatively you could keep the curly brackets, in which case you must explicitly return a value. The advantage of curly brackets is that you can have multiple statements in the function body. Whereas without them you can only have a single expression.

return (
  <View>
    {favoriteTeams.map((item) => {
      return <Text>{item}</Text>
    })}
  </View>
)

For details see: Arrow function expressions - Function body and Arrow function without curly braces

  • Related