2

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?

2
  • 1
    use setState and pass in a function. You can declare state changes separately from the component classes. Basically take your merging of cards and create a function out of it and pass it into setState({}) Here is Dan's tweet regarding this. twitter.com/dan_abramov/status/824308413559668744/photo/… Commented Apr 18, 2018 at 15:09
  • @iceveda06 thanks :) the tweet you shared it very helpful(not for this question, but my another question) :) Commented Apr 19, 2018 at 1:36

2 Answers 2

1

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]
}))
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Moti, thanks for your answer. I have tried the spread operator, it does add the updated card into cards array, but it also add all other cards which are existed already into the state.cards array. I found another way to do it, will post it here.
1

Object.assign() is the solution for me.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.