Laney Williams
Laney Williams

Reputation: 593

Is it possible to have more than one parameters in data for a FlatList?

Like this for example:

<FlatList data={ this.state.foods, this.state.trees }
          renderItem={({item}) => <View><Text>{item.food}</Text><Text>{item.tree}</Text></View>
/>

As long as I have the same key (id), is it possible this can work like this?

this.state.foods:

[{
  "id": "1",
  "food":"chicken",
  "cal":"1000",
}]

this.state.trees:

[{
  "id": "1",
  "tree":"pine",
  "size":"10",
}]

EDIT:

    render(){
      const {trees, foods} = this.state
const combinedArray = trees.map(tree => Object.assign(tree, foods.find(food => food.id == tree.id)));
      return(




    componentDidUpdate(prevProps, prevState) {
      if (!prevState.foods) {

        fetch('https://www.example.com/React/food.php')
         .then((response) => response.json())
         .then((responseJson) => {
           this.setState({
             isLoading: false,
             foods:  responseJson.map(item => ({ ...item, progress: new Animated.Value(0), unprogress: new Animated.Value(1) }))

             }, function() {

           });
         })
         .catch((error) => {
           //console.error(error);
         });
         fetch('https://www.example.com/React/tree.php')
            .then((response) => response.json())
            .then((responseJson) => {
              this.setState({
                isLoading: false,
                trees:  responseJson
                }, function() {

              });
            })
            .catch((error) => {
              //console.error(error);
            });
}
}

Upvotes: 0

Views: 38

Answers (1)

Pritish Vaidya
Pritish Vaidya

Reputation: 22189

You need to supply a single array to a Flatlist data.

You can group the objects based on id and use them

const {trees, foods} = this.state
const combinedArray = trees.map(tree => Object.assign(tree, foods.find(food => food.id == tree.id)));

and then use combinedArray in the Flatlist

If your state is undefined or null initially then you need to add

constructor(props) {
    super(props)
    this.state = {
      trees: [],
      foods: []
    }
   }

to your class component.

Upvotes: 1

Related Questions