1

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?

1
  • It's empty outside the function because you're working with asynchronous code; you're logging it before it has loaded from the api. Commented Jun 21, 2021 at 18:13

1 Answer 1

1

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 } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.