OM62DwC76p
OM62DwC76p

Reputation: 131

react firebase array length 0

I took the data in firebase and setState, this.state.data array is stamped with 0.

I do not know why, I need your help.

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


componentDidMount(){
    this.getData();
}

getData(){
    const arrayItem = [];
    firebase.database().ref('data').on('value', (snapshot) =>{
        snapshot.forEach(function(childSnap){
            arrayItem.push({
                key:childSnap.key,
                data:childSnap.val()
            })
        })
    })
    this.setState({
        data:arrayItem
    })
}

render() {
    {console.log(this.state.data)}

enter image description here

Upvotes: 2

Views: 684

Answers (1)

Tholle
Tholle

Reputation: 112897

The firebase logic is asynchronous, so you must use setState inside of the on callback, or the arrayItem array will be empty.

Example

getData() {
  firebase
    .database()
    .ref("data")
    .on("value", snapshot => {
      const data = [];

      snapshot.forEach(function(childSnap) {
        data.push({
          key: childSnap.key,
          data: childSnap.val()
        });
      });

      this.setState({ data });
    });
}

Upvotes: 3

Related Questions