Nina
Nina

Reputation: 509

React: How to change the state of a variable?

I've queried some data from Firebase realtime database and now I'm trying to add it to a variable. I'm sure that the querying works, because if I console.log(dataSnapshot) it logs the correct data (which is 001). However, when I'm trying to create a variable out of that number it doesn't return anything.

Here is a part of my code:

class Table extends Component {
  constructor(props) {
    super(props);
    this.state = { timestamps: [], user: auth().currentUser, serial: "" };
  }

  componentDidMount() {
    const uid = this.state.user.uid;
    console.log(uid);
    const serial = this.state.serial;
    const serialRef = db.ref(uid + "/serial");
    serialRef.once("value").then(function (dataSnapshot) {
      console.log(dataSnapshot.val());
      this.setState({ serial: dataSnapshot.val() });
    });
    console.log(serial);

Here is a screenshot of my console

Thanks in advance!

Upvotes: 0

Views: 126

Answers (1)

Rishi Desai
Rishi Desai

Reputation: 109

This is happening because you are logging your state variable serial to the console before its value is getting changed(asynchronous behaviour). Hence you are getting your serial variable as the original one.
If you wish to console.log your state variable serial in another variable immediately after setState then do the following:

componentDidMount() {
    const uid = this.state.user.uid;
    console.log(uid);
    let serial = this.state.serial;
    const serialRef = db.ref(uid + "/serial");
    serialRef.once("value").then(function (dataSnapshot) {
      console.log(dataSnapshot.val());
      this.setState({ serial: dataSnapshot.val() }, () => {
          serial = this.state.serial 
          console.log(serial)
        });
      });
    })
}

setState accepts a callback as an optional second parameter.

Upvotes: 1

Related Questions