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.

Originally published at 500tech.com.

--

--

http://adamklein.dev/ I write code, and speak about it

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store