Search code examples
firebasereact-nativereact-native-flatlist

How to fetch Firebase data, store it Into an array and then display it using flatlist?


I am fetching data from firebase and storing them into array. Now I want to display them using flatlist, but I don't know how?

class HomeScreen extends Component{

  constructor(props){
    super(props);
    this.state={
      menu:[]
    }
  }

  // componentDidMount() {
  //   firebase.auth().onAuthStateChanged(authenticate => {
  //     if (authenticate) {
  //       this.props.navigation.replace("Home");
  //     } else {
  //       this.props.navigation.replace("login");
  //     }
  //   });
  // }

   componentDidMount() {
    firebase.database().ref('menu/starter/').once('value').then(snapshot => {
       var items = [];
       snapshot.forEach((child) => {
         items.push({
            name: child.val().name,
            image: child.val().image,
            price: child.val().price,
         });
      });
      this.setState({ menu: items});
      console.log(this.state.menu)
  });
  }

  render(){
    return(
     <View style={styles.container}>
     <Text></Text>
     </View>
    )
  }
}

Solution

  • <FlatList 
    data={this.state.menu}
    keyExtractor={elem => elem.name}
    renderItem={elem => (<View><Text>{elem.item.name}</Text></View>)}
    />
    

    renderItem is the callback to render each of your array item