I use redux with normalizr to normalize the response from server, basically follow the real-world example. This way entities
reducer is very simple, just merge the response. The problem I have right now is kind of delete
operation. I've found this issue#21 of normalizr repo but still couldn't figure out how to solve this. For example,
Current state is
{
entities:
product_categories: {
...
13: {
...
products: ["1", "2"], <--------------- [i] Current state
...
}
},
products: {
1: {
id: "1"
}
}
}
The normalized response is
{
...
product_categories: {
...
13: {
...
products: ["1"], <---------------- [2] Normalized result
}
...
}
As you can see, the backend api just returns all product ids that belonged to this category, in this case "2" is detached. When 'entities' reducer merges the this response, "2" is still hanging around. Right now I just reload the page but i'm wondering if there's a better way to handle this case?
In entities
reducer, I just merge it like in real-world example.
return merge({}, state, action.payload.entities);
Just don't worry about it being there. Think of your state as of a database. You don't truly delete records from the database either to avoid complicated cascades—usually you just change their status in the database. Similarly, with Normalizer, instead of truly deleting the entities, let them be in cache until the user leaves the page!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With