I need to be able to switch items in an array on state using the immutability helper so as to not mutate state directly.
This is the behavior I am looking to achieve (i.e. switching positions 2 with 3)
[
{ key: 'banana'},
{ key: 'apple'},
{ key: 'orange'}
]
to become
[
{ key: 'banana'},
{ key: 'orange'},
{ key: 'apple'}
]
The code below is generating what I thought was going to accomplish this
immutableFruit = {}
let tempFruit = fruits[2]
immutableFruit[2] = { $set: fruits[1] }
immutableFruit[1] = { $set: tempFruit }
this.setState({fruits: immutableFruit})
When logging this to the console I get what I expect
1:
$set: { key: 'orange' }
2:
$set: { key: 'apple' }
So, in my mind, the state should reflect this change, but it doesn't something I didn't expect to, it switches one of the items, but fails to replace the other.
This is what the resulting state array actually looks like
[
{ key: 'banana'},
{ key: 'orange'},
{ key: 'orange'}
]
So, in short, I end up with two items in the list that are identical.
Is $set not the correct way to do this? When looking through the immutability helper documentation I didn't find any examples of this behavior or commands that perhaps are better fits for swapping elements in an array