3

So the problem I'm having is that the setState method doesn't seem to want to update the state of my array questions. But when I use console.log(returnArr) the console prints my desired item from firebase.

What I'm I doing wrong?

export default class App extends React.Component {
  constructor() {
    super();
    this.state = {
      questions: [],
      current_question: 0
    };
  }

  componentDidMount() {
    var rootRef = firebase.database().ref();
    var ref = rootRef.child("Geography");
    var returnArr = [];

    ref
      .once("value")
      .then(function(snapshot) {
        snapshot.forEach(function(childSnapshot) {
          var item = childSnapshot.val();
          item.key = childSnapshot.key;

          if (item.key === "2") {
            returnArr.push(item.Question);
            setState = () => ({
              questions: returnArr
            });
            console.log(returnArr);
          }
        });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    // ...
  }
}

2 Answers 2

1

setState is a function you should call, not an object you should assign a new value to.

If you want to use this inside the firebase callback function you must either bind the function to this or use an arrow function. You most likely want to set the array in state after the entire snapshot has been processed.

Example

class App extends React.Component {
  // ...

  componentDidMount() {
    firebase
      .database()
      .ref()
      .child("Geography")
      .once("value")
      .then(snapshot => {
        const questions = [];

        snapshot.forEach(childSnapshot => {
          const item = childSnapshot.val();
          item.key = childSnapshot.key;

          if (item.key === "2") {
            questions.push(item.Question);
          }
        });

        this.setState({ questions });
      })
      .catch(error => {
        console.error(error);
      });
  }

  // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are not calling setState, you are redefining it.

Change the if to this:

if(item.key === '2'){
  returnArr.push(item.Question)
  this.setState({
      questions: returnArr
  });
  console.log(returnArr)

}

Also, you probably want to call setState after the forEach has ended. In the way you implemented, setState will be called each time the if code is executed. Moving the setState call out of the forEach will make the setState to be called just once.

1 Comment

Thanks! I get what you're saying but now I get this error instead: 12:56:21: this.setState is not a function. (In 'this.setState({ questions: returnArr })', 'this.setState' is undefined)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.