E
E
Elrock2021-02-07 15:46:23
React
Elrock, 2021-02-07 15:46:23

How to save all values ​​in 1 state when clicking?

I caught a blunt, let's say there is a state = {listItems: null} and when I click, I take some object and throw it there, on the next click I have to take the previous object + the new one and write it to the same state. At the end, the listItem should come out of the new objects, but how to do it. Here is my wrong implementation:

state = {
    listItems: null,
  }
addItem = (itemId) => {
    const newItem = this.props.itemsList.filter(
      item => itemId === item.id
    )
    this.setState(state => ({
       listItems: [state.listItems, newItem[0]]
    }))
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abberati, 2021-02-07
@Elrock

state = {
    listItems: [],
}

A
Alexander Cheremkhin, 2021-02-07
@Che603000

state = {
    listItems: []
  }
addItem = (itemId) => {
    const newItem = this.props.itemsList.find(item => itemId === item.id);
    
    newItem && this.setState(state => ({
       ...state,
       listItems: [...state.listItems, newItem]
    }))
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question