Home > Mobile >  Component array not shown in React Native?
Component array not shown in React Native?

Time:09-17

I'm new to React Native, and I wonder why my code isn't working. I know thorugh console.logging that my output array is full with the correct data, but for some reason in the return when I try to write out the output it doesnt seem to writing anything to the mobile screen. I wonder why that might be.

const ChampionScreen = () => {
    const [champions, setChampions] = useState([]);
    var output = [];
    useEffect(() => {
      AxiosService.getChampions()
      .then(data => {
        setChampions(data);
        var champarr =[];
        Object.keys(champions).forEach(function(key){
          champarr.push(champions[key]);
        }) 
        for(let i = 0; i < champarr.length;i  ){
          let champion = JSON.parse(JSON.stringify(champarr[i]));
          var tempItem = (
            <View key={i}>
              <Text>{champion.name}</Text>
            </View>
          );
          output[i] = (tempItem);
        }
      }).catch(err => console.error(err))
    },[])

    return (
      <ScrollView>
        <View>
          {output}
        </View>
      </ScrollView>
    )
}

CodePudding user response:

you did not define output as a state variable and it will not trigger a render that way. after that, when you are mapping the data object with Object.keys method, you are kind of going with luck because the state updates are asyncronous, so you should not set the state and immediately use the state, use the data you already fetched. here it is:

const ChampionScreen = () => {
    const [champions, setChampions] = useState([]);
    const [output, setOutput] = useState([]);

    useEffect(() => {
      AxiosService.getChampions()
      .then(data => {
        setChampions(data);
        var champarr = [];
        let axiosOutput = [];
        Object.keys(data).forEach(function(key){
          champarr.push(data[key]);
        }) 
        for(let i = 0; i < champarr.length;i  ){
          let champion = JSON.parse(JSON.stringify(champarr[i]));
          var tempItem = (
            <View key={i}>
              <Text>{champion.name}</Text>
            </View>
          );
          axiosOutput.push(tempItem);
        }
        setOutput(axiosOutput)
      }).catch(err => console.error(err))
    },[])

    return (
      <ScrollView>
        <View>
          {output}
        </View>
      </ScrollView>
    )
}

  • Related