Search code examples
reactjsreduxnormalizr

Modelling data based on a time range using redux/normalizr


I've have the following data coming from a node backend:

Endpoint:

/user/:id?startDate=2011-10-05T14:48:00.000Z&endDate=2011-10-05T14:48:00.000Z

[
   {
      "name": "Tom",
      "createdAt": "2011-10-05T14:48:00.000Z",
      "updatedAt": "2011-10-05T14:48:00.000Z",
      ...
      "metadata": {
         "activeHours": 134.45,
         "afkHours": 134.45
      }
   },
   {
      ...
   }
]

In this data, the only thing modified between date changes is activeHours and afkHours.

These users and the date that the endpoint was called with must be synced across all pages.

The simple approach would be to put this in a users reducer, something like:

{
   users: [...],
   startDate: "",
   endDate: ""
}

However I'm currently using normalizr with these users and with that I have a single action named ADD_ENTITIES. Having an entities reducer seems very beneficial as we do have other entities that can be nicely normalized with these users, however I don't want to pollute the entities state with almost "tacked on" startDate and endDate to sync across all pages.

On to my question:

Is there a better way to model this problem using normalizr, Where your key is not only ID but also a date range?

Or should I look at breaking this out into a separate reducer as above?


Solution

  • Not sure if I completely understood the problem here.

    Is the startDate and endDate fields, different for each user ? If yes, then you may need to add those fields in the normalized entity object for those users.

    If those are common fields for all the users, you can create a separate entity called userDateRange containing those two keys. It doesn't need to be normalized as they are primitive fields.

    {
      "entities": {
        "user": {
          "byId": {
            "user1": {},
            "user2": {}
          },
          "allIds": [
            "user1",
            "user2"
          ]
        }
      },
      "ui": {
        "userDateRange": {
          "start": "2011-10-05T14:48:00.000Z",
          "end": "2011-10-05T14:48:00.000Z"
        }
      }
    }