Redux Bad Practices #6: Mix UI State with Model Data
In a Redux store, you may have both data from the server, together with the UI-related state. For example, you can have a list of products from the server, and save which one of those the user has selected using a checkbox.
One approach is to store the UI-related state and the data together:
{
products: {
1: { id: 1, name: 'Shirt', isSelected: true },
2: { id: 2, name: 'Pants' }
}
}
This example shows saving the isSelected
attribute on the product object itself. In case you need to refresh the data from the server, you will override the user selection, or you'll need to perform a smart merge on the data to avoid losing it.
A better approach would be to always separate UI and model data:
{
products: {
1: { id: 1, name: 'Shirt' },
2: { id: 2, name: 'Pants' }
},
selectedProducts: { 1: true }
}
Saving the selection state outside the actual data will ensure you can always pull it from the server without worrying about overriding anything.
All articles in this series:
https://medium.com/@adamklein_66511/redux-bad-practices-1-lists-as-arrays-9115ba87b0ce
https://medium.com/@adamklein_66511/redux-bad-practices-2-duplicate-code-9f2f3d774d4d
https://medium.com/@adamklein_66511/redux-bad-practices-3-nested-state-6eebf1a410df
https://medium.com/@adamklein_66511/redux-bad-practices-5-duplicate-state-996d259758e3
https://medium.com/@adamklein_66511/redux-bad-practices-6-new-objects-on-the-fly-c38b503948a5
https://medium.com/@adamklein_66511/redux-bad-practices-7-mix-ui-state-with-model-data-cdca6c8d8fd9
Originally published at 500tech.com.