Franva
Franva

Reputation: 7077

Reactjs Update a single element in an array inside state

I have a component:

constructor(props) {
    super(props);

    this.state = {
        cards: []
    };
}

Inside the this.state.cards array, for each card the data structure looks like:

{
  movie: v,
  ids: v.id,
  goodDeal: `Cheapest price is ... at ...`
}

Now, I need to merge another cards(say cards2) array into my current state.cards array:

componentDidMount(){
    cards2.map((v, i)=>{
       var existedCard = this.state.cards.find((cv, ci)=>{
           if(cv.code === v.code){
               return cv;
           }
       })

       if(existedCard){
          existedCard.ids += v.id;

          this.setState((prevState, pros)=> {
              // then update the state, but how?                   
          })
       }
       else {
          // add the new card into the current cards array
       }
    })
}

As you can see, if I found an card(newCard) in card2 which is also in card1(which is the state.cards), then I add the newCard.id into the existedCard.ids. Then I want to call setState() to update the state.

But how?

Upvotes: 2

Views: 666

Answers (2)

Franva
Franva

Reputation: 7077

Object.assign() is the solution for me.

            this.setState((prevState, props) => {
                return Object.assign({}, prevState, existedCard);
            });

Upvotes: 1

Moti Korets
Moti Korets

Reputation: 3748

Use the setState((prevState) => {/* method that returns nextState*/}) form.
To add the new object run

this.setState(prevState => ({
  cards: prevState.cards.concat(existedCard)
}))

For update you would have to filter out the old object first

this.setState(prevState => ({
  cards: prevState.cards.filter( card => card.id !== v.id).concat(existedCard)
}))

You can also use the spread operator if its is supported by your target (build) system.

this.setState(prevState => ({
  cards: [...prevState.cards, existedCard]
}))

Upvotes: 1

Related Questions