I'm experimenting with Firebase and I've written code like the following before but for some reason I am not getting what I expect.
When the React component below mounts I expect the this.state.clients
array to be populated with the queried firebase data. The problem is that when the component loads this.state.clients
is empty (and there are no errors). I've also included a snap shot image of my schema. I am using the "reatime database" and not the newer "Cloud Firestore".
Thank you!
Code
import React, {Component} from 'react';
import firebase from 'firebase/app';
class Dashboard extends Component{
constructor(props){
super(props)
this.state = {
clients: []
}
this.clientsRef = firebase.database().ref('clients')
}
componentDidMount(){
this.clientsRef.on('child_added', snapshot => {
const client = snapshot.val();
client.key = snapshot.key;
this.setState({ clients: this.state.clients.concat( client ) })
});
}
render(){
console.log(this.state.clients); // <---- is an empty array after component mounts but *should* contain data per the above firebase query
return(
<div>
<h2>All Clients </h2>
</div>
)
}
}
export default Dashboard
It's an empty array because you declared it an empty array in the constructor. The 'child added' event hasn't fired yet. If you go to your firebase console and manually add an item to 'clients' then this will trigger the 'child added' event and the event will show up in your UI. Replace 'child_added' with 'value' if you want the value of all existing events onload.
我忘记在“规则”选项卡中设置读取权限
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.