1

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
1
  • Fixed it. The reason was because i used the index as the unique key for each element. Using something else (eg. unique name) for the key resolved this issue. Thanks. Commented Dec 19, 2017 at 20:13

2 Answers 2

1

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

2 Comments

sorry i corrected my code. I did accounts = state.accounts.map... and then edited the accounts. And i still get the same bizarre behavior
map does not clone the array, I have edited my answer
1

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)]})
}

1 Comment

Tried it, does not fix the issue. I already confirmed that using a brand new array will not resolve it.

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.