0
votes

I'm new to React Native and I wanted to make a simple app using Marvel API and for that I'm using API wrapper. I want to display infinite scroll view using VirtualizedList. And here is the question: what to pass in renderItem and data components? And is the 'findCharacters' const good written or should i change something? And lastly, should I change VirtualizedList to FlatList or ScrollView? My code is below

   const findCharacters = marvel.characters.findAll()
  .then(console.log)
  .fail(console.error)
  .done();


  return (
    <View style={styles.container}>
      <VirtualizedList
      data={/* what to pass here? */}
      renderItem={/* what to pass here? */} />
    </View>
  );
}
1

1 Answers

0
votes

It's a good idea to use meaningful variable names, in your case something like getMarvelCharacters sounds good.

API response gives out a JSON containing data which is an array of objects of marvel characters. Pass this to VirtualizedList's data param.

As for the renderItem prop it's basically about how you want to render each of the objects in data i.e marvel characters. Read the full documentation for VirtualizedList over here.

So the whole code can be something like this.

const [marvelCharacters, setMarvelCharacters] = useState([]);

const getMarvelCharacters = marvel.characters.findAll()
  .then((err, results) => {
    setMarvelCharacters(results.data);
  })
  .fail(console.error)
  .done();

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

const CharacterItem = ({ title }) => (
  <View>
    <Text>{title}</Text>
  </View>
);

return (
    <View style={styles.container}>
      <VirtualizedList
      data={marvelCharacters}
      renderItem={({ item }) => <CharacterItem title={item.title}/>} />}
    </View>
  );