All Ruby on Rails Node JS Android iOS React Native Frontend

Data Normalization in Frontend Apps Using Normalizr and JSON API Normalizer

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

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.

The solution for that is Normalizr:

The only requirement is that each entity (post, comment, author) has the `id` property.

Example below shows us the data before and after normalization:

Pros of this solution:

  • updating comment and author data is very easy
  • you can easily show all posts, authors and comments
  • there is no data duplication

Cons:

  • displaying few comments in a post requires passing an object with all comments
  • in small apps without a lot of data duplication, normalizing data may not be necessary

Summary

JSON API Normalizer automatically (without configuration) transforms data in JSON API standard to normalized data

Normalizr allows to normalize data using schemas

We're building our future. Let's do this right - join us
New Call-to-action
READ ALSO FROM API
Read also
Need a successful project?
Estimate project or contact us