As we continue to improve our app, we struggled with the lack of consistency in our models, even if they were immutable. They were generic types (i.e. Map, Array), so we couldn’t precisely validated propTypes given to our components. :cyclone:
As Immutable.js was already in our project, we thought we could take advantage of the Immutable.Record to build our models to:
- export a clear type for each model;
- define model attributes;
- expose getters if needed.
So, we can start be defining our first model, a Task record with default value and getters:
Alongside this model representing a unique task, we define another record to represent tasks list, TaskMap :
We could now make the most of these two records and refactor our Redux Reducer to ensure that our store state is a TaskMap with only Task records as values ( keys are Task ids):
Finally, we can create a container to present our data and connect it to our application state. We import the TaskMap model to validate our props:
And we do the same in our TaskListItem children to ensure that this component receives a Task model:
Now, if we mess up with the TaskListItem component, a clear message will pop up in our console. :eyes:
The message is clear enough to focus our attention on the wrong type given in the component container: it increases the component reusability and gives direct feedback if something in our app state is wrong. :ok_hand:
That’s all folks 🙂 Easy to setup, great to use. We now have a consistent model representation for our data. Plus, the records are extendable and we can define on them… testing and debugging is easier now /o/ Next step could be defining types with Flow or Typescript… See you later!
Credit to Draft.js , a project maintained by Facebook, and from where great ideas can be taken about Immutable data structure, tests, code clarity…
Leave email, sticky notes behind. Start tracking your work with your team, clients and partners in Azendoo ( https://www.azendoo.com ).