OM The Eternity
OM The Eternity

Reputation: 16194

How to prepend a value to an array inside the object of state in Reactjs

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

Answers (2)

gazdagergo
gazdagergo

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

san
san

Reputation: 1693

You can try:

this.setState((state) => {
   return {
     transition: {
       ...state.transition,
       completedStages: ['SR', ...state.transition.completedStages]
     }
   }
})

Upvotes: 2

Related Questions