M
M
MarEeeeeee2021-04-28 19:13:31
React
MarEeeeeee, 2021-04-28 19:13:31

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,
        }
      }


There was this solution:
componentDidMount(){
        firebase.database().ref('lectures/' + "421452").once('value', (data)=>{
            this.setState({

            })  
        })
    }

but I would like to immediately write the data to the state, and not overwrite them at the time of the mount.
I also tried to shove setState inside the constructor, but it seems to me that this is also wrong.
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()
            })  
        })
      }


how to solve this problem correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tehfreak, 2021-04-28
@MarEeeeeee

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 question

Ask a Question

731 491 924 answers to any question