Reputation: 131
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)}
Upvotes: 2
Views: 684
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