3

I'm trying to add an object to an array in a reducer, and after that, I would like to sort it by date (I can try to insert in order, but I think is more or less the same effort).

I'm using immer to handle the reducer immutability:

const newState = produce(prevState, (draftState) => {
  console.log(draftState);
  draftState.status = COMPLETE;
  draftState.current.entries.push(json.data);
    if (json.included) draftState.current.included.push(json.included);
});
return { ...initialState, ...newState };

The console.log showed there is printing this:

Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true

So.. I don't really know how can I sort the draftState.current.entries array using immer.

Any suggestions are welcome,

Thanks

teo
  • 73
  • 7

2 Answers2

3

I ended up sorting the array first and then assigning that ordered array to draftState.current.entries

let sortedEntries = prevState.current.entries.slice();
sortedEntries.push(json.data);
sortedEntries.sort((a, b) => new Date(b?.attributes?.date) - new Date(a?.attributes?.date));
const newState = produce(prevState, (draftState) => {
  draftState.status = COMPLETE;
  draftState.current.entries = sortedEntries;
  if (json.included) draftState.current.included.push(json.included);
});

return { ...initialState, ...newState };
teo
  • 73
  • 7
0

To sort an array, without mutating the original array:

  • Call the slice() method on the array to get a copy.
  • Call the sort() method on the copied array.
  • The sort method will sort the copied array, without mutating the original.
Raimo Haikari
  • 121
  • 1
  • 3
  • 1
    This does not seem to suggest an immer-based solution. – Lajos Arpad Jun 14 '22 at 23:33
  • You are propably right. My react / redux project stopped working after I updated React and Redux -versions. And the thing that was causing the problem was sorting an arrays and by means on slice() - method I was able to fix my problem and thought I could help if someone else faces same situation. – Raimo Haikari Jun 15 '22 at 12:18
  • 1
    The idea is good, but I cannot upvote it, because the question asked for immer-based solutions. – Lajos Arpad Jun 16 '22 at 10:18