Reputation: 3831
I have a normalised Redux data structure indexed by a string ID. Amongst other properties, each object in the state has a sequenceNumber
which is used to display it in order in a list or grid. The items can be dragged and dropped to reorder them.
I'm struggling to find a neat, pure approach to updating the sequence numbers. What is a good way to do this in a Redux reducer?
My current state
data structure is essentially:
{
'asdf': { title: 'Item 1', sequence: 0, ... },
'1234': { title: 'Item 2', sequence: 1, ... },
'zzzz': { title: 'Item 3', sequence: 2, ... }
}
My action is
{ type: REORDER_ITEMS, oldRow: 1, newRow: 0 }
Which should result in the state
{
'asdf': { title: 'Item 1', sequence: 1, ... },
'1234': { title: 'Item 2', sequence: 0, ... },
'zzzz': { title: 'Item 3', sequence: 2, ... }
}
My current reducer uses Object.keys(state).reduce()
to loop through the items and modify the sequence
one by one, depending on whether they are equal, greater or lesser than the desired row numbers. Is there a neater way to manage this?
Upvotes: 1
Views: 486
Reputation: 773
You could normalize a step further : Extract the sequence in a separate state slice and store the order as an array of ids.
{
items : {
'asdf': { title: 'Item 1', ... },
'1234': { title: 'Item 2', ... },
'zzzz': { title: 'Item 3', ... }
},
sequence: ['1234', 'asdf', 'zzzz']
}
This way, you could have a separate reducer to handle actions modifying your sequence, only using array operations.
Upvotes: 4