Chick Evans
Chick Evans

Reputation: 47

Set state of nested array

I have this class:

class Board {
    this.state = {
        lists : [{
            id: 0, 
            title: 'To Do',
            cards : [{id : 0}]
        }]
    }

And want to use setState on the 'cards' array inside of the 'lists' state array. Previously, I had the cards array in a child component but I have now moved it up to the Board class. This is the function that I had before.

deleteCards(id){
    this.setState({
        cards: this.state.cards.filter(card => card.id !== id)
    });
}

How can I change it so that it works now that cards is inside another array?

I was unable to solve it looking at these posts:

ReactJS - setState of Object key in Array

How to edit an item in a state array?

Upvotes: 3

Views: 8826

Answers (2)

chrisbot
chrisbot

Reputation: 360

To do it all within setState (note that the first argument to setState is an updater function where its first argument is a reference to the previous state):

If you can provide the listId from the caller:

deleteCards(listId, cardId) {
  this.setState(prevState => ({
    lists: prevState.lists.map((list) => {
      if (list.id !== listId) {
        return list
      }

      return {
        ...list,
        cards: list.cards.filter(card => card.id !== cardId) 
      }
    })
  }))
}

If you can not provide the listId from the caller:

deleteCards(id) {
  this.setState(prevState => ({
    lists: prevState.lists.map((list) => {
      if (list.cards.some(card => card.id === id)) {
        return {
          ...list,
          cards: list.cards.filter(card => card.id !== id) 
        }
      }

      return list
    })
  }))
}

Upvotes: 5

Gavin Thomas
Gavin Thomas

Reputation: 1867

You should attempt to use the new rest and spread syntax...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

const newListItem = {this.state.lists[0].cards.filter....} 

this.setState({lists: [...this.state.lists.cards, newListItem]})

I would have made this a comment but it would be pretty hard to read. This is just an example you need to actually write a filter.

Upvotes: 1

Related Questions