Data normalization is useful when app state is getting too big, has deeply nested information and difficult to use. When normalizing data we need to follow few rules:
data structure should be flat
each entity should be stored as different object property
relationships with other entities should be created based on ids
This post will present two packages that help with data normalization in frontend apps.
JSON API Normalizer
JSON API is a standard that helps API developers to create consistent responses and API users to create requests. You can read more about JSON API in documentation.
Responses in JSON API format are very easy to use but we can make them even better. We will use JSON API Normalizer to normalize our data.
Example below shows us the data before and after normalization:
JSON API Normalizer created two entities `articles` and `people`. This helps us to check if response has the data that we wanted, without checking property `type`.
Normalized data is a lot easier to use in frontend. Using JSON API Normalizer doesn’t require much effort and configuration.
Normalizr is a very useful package that uses custom schemas definition to create normalized data.
When fetching data about blog post we can expect data in format like this:
This kind of data structure seems totally fine, but when we will store more blog posts we will observe duplication of authors data. As our blog grows, we may add categories and relationships between comments and users. There is no need to store all of that in one object.