Reputation: 709
Not sure where I'm going wrong but I have two buttons that act as a counter
this.state= { currentQuestionId: 1 }
Depending on the state of currentQuestionId
, it renders specific divs
I have this function
checkButton = button => {
if (button.id === 3) {
this.setState(state => ({
userAnswers: state.userAnswers.concat([button]),
currentQuestionId: (state.currentQuestionId = 5),
}))
console.log('questionState', this.state.currentQuestionId)
} else {
this.selectAnswer(button)
}
console.log('button pressed', button.id)
}
If a specific button is pressed, it sets currentQuestionId = 5
,
I also have another function that decreases currentQuestionId
previousQuestion = () => {
this.setState(prevState => ({ currentQuestionId: prevState.currentQuestionId - 1 }))
}
Basically, once my CheckButton function
fires, it sets my currentQuestionId = 5
, and when previousQuestion
fires, I want it to return the state of currentQuestionId
before it was set to 5
What am I missing?
Upvotes: 2
Views: 180
Reputation: 446
I think you're understanding prevState
to mean the value that a state was in before it was changed to another value. For example, you're expecting that if currentQuestionId = 3
, then we set currentQuestionId = 5
, that prevState
of currentQuestionId
is equal to 3. This isn't what prevState
is used for.
prevState
allows you to perform an atomic update on a value to ensure correctness:
this.setState(prevState => ({ currentQuestionId: prevState.currentQuestionId - 1 }))
Whereas using this.state
is performed asynchronously:
this.setState(() => ({ currentQuestionId: this.state.currentQuestionId - 1 }))
However, these both reduce currentQuestionId
by 1. More info regarding the usage of prevState
and how it works here.
To answer your question, what you want to do is to add another state variable to your class called previousQuestionId
, and set that to currentQuestionId
, before updating currentQuestionId
to a new value. That way you can keep track of the previous value and set it using this:
previousQuestion = () => {
this.setState({ currentQuestionId: this.state.previousQuestionId }))
}
EDIT: A better way to track the previous questions is to use a stack. You can push new values to it when a new question ID is selected, and pop values off of it when you run previousQuestion
.
Upvotes: 4