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
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 };