Answer the question
In order to leave comments, you need to log in
How to write data from fireBase to the state of a React component?
Hello, there is a react component that reads information from the database. The query to the database returns a promise. I don't understand how to immediately write information from the database inside this.state.
var currentData = {
idLecture: "421452",
nameLecture: "Advansed React",
numberGoodMarks: 42,
numberSatisfactoryMarks: 356,
numberBadMarks: 14
}
class EvaluationLecture extends React.Component{
constructor(props) {
super(props)
this.state = {
lecture:{
idLecture: currentData.idLecture,
nameLecture: currentData.nameLecture,
numberGoodMarks: currentData.numberGoodMarks,
numberSatisfactoryMarks: currentData.numberSatisfactoryMarks,
numberBadMarks: firebase.database().ref('lectures/' + "421452").once('value', (data)=>{
return data.val().numberBadMarks; // очевидно ошибочно решение, но смысл должен быть таким. из БД сразу в стейт
})
},
isVoted: localStorage.getItem(currentData.idLecture) === null ? false : true,
}
}
componentDidMount(){
firebase.database().ref('lectures/' + "421452").once('value', (data)=>{
this.setState({
})
})
}
class EvaluationLecture extends React.Component{
constructor(props) {
super(props)
this.state = {
lecture:{},
isVoted: localStorage.getItem(currentData.idLecture) === null ? false : true,
}
firebase.database().ref('lectures/' + "421452").once('value', (data)=>{
this.setState({
lecture: data.val()
})
})
}
Answer the question
In order to leave comments, you need to log in
To immediately write data to the state (in the component's constructor), this data must be immediately available, for example, in props. If you need to perform an asynchronous operation and write the result to state, then you need to do this in componentDidMount:
class extends React.Component {
async componentDidMount() {
this.setState({
data: (await dataRef.once('value')).val()
})
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question