Daskus
Daskus

Reputation: 969

Sort ids by entity property in redux store

I have a problem sorting the data in my redux-store.

My store looks like this:

state = {
  ids: [1,2,3,4, /*...*/],
  entities: {
    1: {
      id: 1,
      time: 50
    }
    //...
  }
};

In my reducer function I want to sort the ids, in this way my data will always be sorted and ready to use, without needing to sort it every time:

case LOAD_LIST_SUCCESS:
  return Object.assign({}, state,
    {ids: [state.ids, ...action.payload.normalized.result].sort()}, //Here is my problem...
    {entities: [...state.entities, ...action.payload.normalized.entities.items});

How can I sort the ids array by the entities time property?

Upvotes: 0

Views: 1796

Answers (1)

Mark Chandler
Mark Chandler

Reputation: 338

To sort by the time property, you would need to do something more advanced with the sort function.

I've made a quick example:

[state.ids, ...action.payload.normalized.result].sort((id1, id2) => {
  const entity1 = state.entities[id1]
  const entity2 = state.entities[id2]

  if (entity1.time < entity2.time) {
    return -1
  }

  if (entity1.time > entity2.time) {
    return 1
  }

  return 0
})

However, this approach will not take into account any normalized entities attached to the current action because the state's entities list will have not been updated yet, so you might need to assign the new state to a variable, then sort the ids based on the entities in the new state, and THEN return it as the result of the LOAD_LIST_SUCCESS case.

Upvotes: 2

Related Questions