goldensausage
goldensausage

Reputation: 239

Reactjs: remove array element, element states don't follow

Not sure how to word this question properly in the title.

Scenario: React app displays an array of 3 Elements (dropdowns), closed by default.

I open the second dropdown:
0: state.isOpen: closed
1: state.isOpen: open
2: state.isOpen: closed

I remove the FIRST element of the array:
0: state.isOpen: closed
1: state.isOpen: open

Weird, because i expect the the new first element to be open and the second to be closed. It appears the states don't follow the elements (eg. second element state will go to the new second elemenet state after removal). I tried not mutating the array, but instead creating a new one and using that to setstate, but same result.

I expect the new [0] to be open and [1] to be closed. How do i do that? Thanks.

//Accounts.js:
accounts.map( () => { return <Account/>})
removeAccount = () => {
    let accounts = this.state.accounts.map(item => return item)
    accounts.splice...
    this.setState({accounts: accounts})
}

//Account.js:
state.isOpen
removeAccount = this.props.removeAccount

Upvotes: 1

Views: 83

Answers (2)

user9116119
user9116119

Reputation:

You can leverage Array.prototype.slice() to return a brand new array that excludes your first element without touching anything else.

See below for a practical example.

removeAccount = () => {
  return this.setState((state) => {accounts: [...state.accounts.slice(1)]})
}

Upvotes: 1

klugjo
klugjo

Reputation: 20885

I think your are not cloning your array properly:

removeAccount = () => {
    let accounts = [...this.state.accounts]; // Cloning first
    accounts = accounts.map(item => return item) // Do your mappings here
    accounts.splice... // Do your modifications here
    this.setState({accounts: accounts}); // Set the new state 
}

Upvotes: 1

Related Questions