Reputation: 16194
I have an initial state as:
this.state = {
transition:{
completedStages:[]
}
}
What I am trying to achieve is, at a function call I can update my state for completedStages
, such that every time the state is updated the value is prepended in the array. Like:
this.state = {
transition:{
completedStages:[SR, RR, BR]
}
}
For this, what I tried is:
let completedStages = [...this.state.transition.completedStages];
completedStages.unshift('SR');
this.setState({
transition:{
completedStages:[completedStages]
}
})
This is messing up my output and giving every added array value in pair of other as key. How can I understand this scenario?
Upvotes: 0
Views: 92
Reputation: 6691
Just prepend it like this. You can use the function way of setState either:
this.setState(prevState => ({
transition:{
completedStages:['SR', ...prevState.transition.completedStages]
}})
Upvotes: 1
Reputation: 1693
You can try:
this.setState((state) => {
return {
transition: {
...state.transition,
completedStages: ['SR', ...state.transition.completedStages]
}
}
})
Upvotes: 2