Thomas Hietkamp
Thomas Hietkamp

Reputation: 96

Firebase with react native to array

I am working on the backend of my React Native project with Firebase. I want to retrieve records from the database and render a flat ist from an array. I tried to make an array, but outside the function, it is empty again...

Here is my code:

  var brand_list = [] // the list
  //retrieve record from firebase database
  firebase.firestore().collection('Brand').get().then((querySnapshot) => {
    querySnapshot.forEach(snapshot => {
        let data = snapshot.data();
        brand_list.push(data);
    })
    console.log(brand_list) // contains the records
  })
  console.log(brand_list) // empty again

What is a possible fix for this, so I can nicely render my flatlist?

Upvotes: 1

Views: 616

Answers (1)

HackRx
HackRx

Reputation: 318

In react-native you need to use the state to first initialize the variable and then use setState() to update the variable, setState() functions tell the react-native to update the UI. if the array is empty outside the function that means you need to use async-await here, to make sure you await for a function to be finished first. I think you try this:

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

async fetchList(){
await firebase.firestore().collection('Brand').get().then((querySnapshot) => {
    querySnapshot.forEach(snapshot => {
        let data = snapshot.data();
        this.setState((prevState)=>{
dataFetched:[...prevState.dataFetched, data]
});
    })
    console.log(this.state.dataFetched); 
// now you can use this.state.dataFetched to update the flatList
}

Upvotes: 1

Related Questions