Boss Nass
Boss Nass

Reputation: 3522

Push data to array within react native

I have been trying to push data from my firebase database to array, though it appears from the login that the data isnt being presented

Below are the logs

[15:36:08] Get Ref https://xxxx.firebaseio.com/merchants
[15:36:08] Gladiator Fitness
[15:36:08] Array undefined

This is the piece of code I am trying to execute

componentWillMount() {
    let initialLoad = true;
    this.setState({loading: true});

    var merchants = [];

    merchantsRef.once('value').then((snapshot) => { // here too!
      // ... and add it to the matches array
      console.log(snapshot.val().business_name)
      merchants.push({
        business_name: snapshot.val().business_name,
        _key: snapshot.key
      })
      console.log("Array " + merchants.business_name)
    }).catch((error) => { // If you are planning to use this here
      console.log('Error fetching merchant data:', error)
    })

    this.setState({
      data: merchants,
      loading: false
    })

    if (initialLoad) {
      this.setState({loading: false});
      initialLoad = false;
    }

  }

Upvotes: 0

Views: 2196

Answers (2)

QuokMoon
QuokMoon

Reputation: 4425

Your data is already in array, check console.log("Array " + merchants.business_name), obvious it gives undefined cause accessing invalid element. Try an access first element in console, like

console.log("Array " + merchants[0].business_name) or 
console.log("Array " + merchants)

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

The call to setState must be inside the value callback:

var merchants = [];

merchantsRef.once('value').then((snapshot) => { // here too!
  // ... and add it to the matches array
  console.log(snapshot.val().business_name)
  merchants.push({
    business_name: snapshot.val().business_name,
    _key: snapshot.key
  })
  console.log("Array " + merchants.business_name)
  this.setState({
    data: merchants,
    loading: false
  })
}).catch((error) => { // If you are planning to use this here
  console.log('Error fetching merchant data:', error)
})

The reason for this is that the callback is called asynchronously, which means that in your code the setState with the merchants array gets called before you populated the array.


The easiest way to see the flow is with a few well placed logging statements:

console.log("Before starting to load");
merchantsRef.once('value').then((snapshot) => { 
  console.log("Data loaded");
})
console.log("After starting to load");

When you run this code, the output is:

Before starting to load

After starting to load

Data loaded

This is probably not what you expected, but perfectly explains why the array is empty when you're calling setState with the merchants array in your code.

Upvotes: 1

Related Questions