Reputation: 1353
First off, I'm still a relative newbie to the world of React & Redux. I'm reading about Normalizing State Shape, and their examples are about storing data by ID. But what if I have data that is keyed on multiple dimensions?
For example, my app is displaying cost data for a given Service ID, which is retrieved from an API. However, the user is able to select a time range. The start and end timestamps are passed to the API, and the API returns the aggregated data over that time range. I want to be able to store all the different time period data in Redux so if the user goes back to a previous time period, that data is already there (our API is slow, so having already loaded data available is critical to user experience).
So not only do I have data keyed by Service ID, but also by Start Time / End Time. Since Redux recommends flat data structures, I wonder how flat should I make it? Because normally, I would store the data like this:
{
costData: {
[service_id]: {
[start_time]: {
[end_time]: {
/* data */
}
}
}
}
}
But that seems to go about the idea of flattening the data. One of my ideas was to generate an ID based on Service ID & Start Time & End Time of the form:
<ServiceID>::<StartTime>::<EndTime>
eg.
00123::1505423419::1505785502
So the data is fairly flat:
{
costData: {
'00123::1505423419::1505785502': {
/* data */
}
}
}
The component can generate this ID and pass it to the fetchCostData()
action, which can dispatch and fetch the data and store that data on that generated ID. But I don't know if that's the best approach. Are there any guidelines or recommendations on how to approach this?
Upvotes: 2
Views: 163
Reputation: 67459
In addition to the other answer, you may want to read the article Advanced Redux Entity Normalization, which describes ways to track additional lookup descriptions of normalized data. I also have some other articles on normalization in the Redux Techniques#Selectors and Normalization section of my React/Redux links list.
Upvotes: 1
Reputation: 217
I recommend using selectors (Reselect) for this nested data, if you're not comfortable with modifying your api.
-> Selectors are the best approach for computing derived data, allowing Redux to store the minimal possible state.
-> Selectors are efficient. A selector is not recomputed unless one of its arguments change.
-> Selectors are composable. They can be used as input to other selectors.
Upvotes: 2