2

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

1 Answer 1

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.