Portable
Portable

Reputation: 823

React setState() doesn't return updated state on callback

I am trying to create a quiz app and in the componentDidMount() function I am trying to update and return some questions. However, when I'm console logging the state after setState(). The same objects are returned.

export default class Multiple extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: [
        {
          id: 1,
          question: "How many in a couple",
          answers: [{ option1: "1", option2: "2", option3: "3", option4: "4" }],
          answer: "2"
        }
      ],
      currentQ: ""
    };
  }

  componentDidMount() {
    const currentQs = this.state.questions;
    console.log(currentQs);
    this.setState(prevState => {
      console.log(prevState);
      return (
        {
          questions: currentQs,
          currentQ: this.getRandomQ(currentQs)
        },
        console.log(this.state)
      );
    });
  }

  getRandomQ(currentQs) {
    const question = currentQs[Math.floor(Math.random() * currentQs.length)];
    return question;
  }

  render() {
    return (
      <div className="container">
        <Quiz
          question={this.state.currentQ.question}
          answers={this.state.currentQ.answers}
          answer={this.currentQ.answer}
        />
      </div>
    );
  }
}

Sorry, I'm new to react and I'm struggling to gauge my way around, especially in creating a quiz application.

Upvotes: 2

Views: 64

Answers (1)

Tholle
Tholle

Reputation: 112777

You are currently returning undefined from the function given to setState because of how the , operator works.

const state = (
  {
    questions: ['foo', 'bar'],
    currentQ: 'bar'
  },
  console.log('baz')
);

console.log(state);

You want to give a function as second argument to setState if you want it be called after the state has been set.

this.setState(
  prevState => {
    console.log(prevState);
    return {
      questions: currentQs,
      currentQ: this.getRandomQ(currentQs)
    };
  },
  () => console.log(this.state)
);

Upvotes: 4

Related Questions