Json-api-normalizer: Why JSON API and Redux Work Best When Used Together

As a web developer, we have to manage the data needed for every application we work on. There are problems when doing so, such as:

  1. Fetch data from the back end.
  2. Store it somewhere locally in the front-end application.
  3. Retrieve the data from the local store and format it as needed by the specific view or screen.

In this article, we are going to discuss about the data usage from JSON, the JSON API and GraphQL back ends, and from that, we can learn the practical way on how to manage front-end application data. As for the real use, let’s imagine that we have carried out a survey that asks the same questions of many users. After each user has given their answers, other users can comment on them if wanted to. Our web app will perform a request to the back end, store the gathered data in the local store and render the content on the page. In order to make it stay simple, we will leave out the answer-creation flow.

Redux Best Practices

What makes Redux the best is that it is changeable no matter what kind of API you consume. It doesn’t matter whether you change your API from JSON to JSON API or even GraphQL and back during development, as long as you keep your data model, so it will not affect the implementation of your state management. Below is the explanation on the best practice using Redux:

  1. Keep Data Flat in the Redux Store

First, here’s the data model:

 

 

Based on the picture above, we have a question data object that might have many post objects. It is possible that each post might have many comment objects. Each post and comment has respectively one author.

Let’s say we have a back end that returns a specific JSON response. It is possible that it would have a carefully nested structure. If you store your data in the same way you do in the store, you will face many problems after that, like, for instance, you might store the same object many times like this:

{

  “text”: “My Post”,

  “author”: {

    “name”: “Yury”,

    “avatar”: “avatar1.png”

  },

  “comments”: [

    {

      “text”: “Awesome Comment”,

      “author”: {

            “name”: “Yury”,

        “avatar”: “avatar1.png”

      }

    }

  ]

}

In the example above, it indicates that we store the same Author object in several places, which is bad, because not only does it need more memory but it also has negative side effects. You would have to pass the whole state and update all instances of the same object especially if somebody changed the user’s avatar in the back end.

To prevent something like that from happening, we can store the data in a flattened structure. This way, each object would be stored only once and would be easily accessible.

{

  “post”: [{

    “id”: 1,

    “text”: “My Post”,

    “author”: { “id”: 1 },

    “comments”: [ { “id”: 1 } ]

  }],

  “comment”: [{

    “id”: 1,

    “text”: “Awesome Comment”

  }],

  “author”: [{

    “name”: “Yury”,

    “avatar”: “avatar1.png”,

    “id”: 1

  }]

 }

  1. Store Collections as Maps Whenever Possible

After we have the data in a good flat structure, we can gradually accumulate the received data, in order for us to reuse it as a cache, to improve performance or for offline use. However, if we combine new data in the existing storage, we have to select only relevant data objects for the specific view. We can store the structure of each JSON document separately to find out which data objects were provided in a specific request to gain this. There is a list of data object IDs that we can use to gather the data from the storage.

Let’s say there is a list of friends of two different users, Alice and Bob. We will then perform two requests to gather the list and review the contents of our storage consequently. Let’s suppose that from the start the storage is empty.

/ALICE/FRIENDS RESPONSE

Here’s the User data object with an ID of 1 and a name, Mike, like this:

{

  “data”: [{

    “type”: “User”,

    “id”: “1”,

    “attributes”: {

      “name”: “Mike”

    }

  }]

}

/BOB/FRIENDS RESPONSE

This is another request that would return a User with the ID of 2 and Kevin as the name:

{

  “data”: [{

    “type”: “User”,

    “id”: “2”,

    “attributes”: {

      “name”: “Kevin”

    }

  }]

}

STORAGE STATE

This is what our storage state would look like:

{

  “users”: [

    {

      “id”: “1”,

      “name”: “Mike”

    },

    {

        “id”: “2”,

        “name”: “Kevin”

    }

  ]

}

STORAGE STATE WITH META DATA

In order to find out or distinguish which data objects in storage are relevant, we have to keep the structure of the JSON API document. With that focus, we can change it into this:

{

  “users”: [

    {

      “id”: “1”,

      “name”: “Mike”

    },

    {

        “id”: “2”,

        “name”: “Kevin”

    }

  ],

  “meta”: {

      “/alice/friends”: [

        {

          “type”: “User”,

          “id”: “1”

        }

      ],

      “/bob/friends”: [

        {

          “type”: “User”,

          “id”: “2”

        }

      ]

  }

}

With this, we can now read the meta data and gather all mentioned data objects. Now here’s the recap of the operations’ complexities:

As can be seen from the picture above, maps certainly works better than arrays because all operations have O(1) as the complexity instead of O(n). If we use a map instead of an array for the User data object, it would be like this:

STORAGE STATE REVISED

{

  “users”: {

      “1”: {

        “name”: “Mike”

      },

      “2”: {

        “name”: “Kevin”

      }

  },

  “meta”: {

      “/alice/friends”: [

        {

          “type”: “User”,

          “id”: “1”

        }

      ],

      “/bob/friends”: [

        {

          “type”: “User”,

           “id”: “2”

        }

      ]

  }

}

Now with this simple method, we can find a specific user by ID almost instantly.

Processing the Data and JSON API

There are many solutions to convert JSON documents to a Redux-friendly form. However, while there is no significant change within the application’s lifecycle, it will cause a failure if things are too dynamic, even though normalizing the function with the provision of a JSON document works great if your data model is known in advance.

Using GraphQL might be possible and interesting as well; however, if our APIs are being consumed by many third parties, we can’t adopt it.

JSON API and Redux

Redux and the JSON API work best together. The data provided by the JSON API in a flat structure by definition conforms nicely with Redux best practices. The data is typified in order to be naturally saved in Redux’s storage in a map with the format type → map of objects.

There are things to consider, though. First, it should be noted that storing the types of data objects “data” and “included” as two separate entitles in the Redux store can violate Redux best practices, as the same data objects would be stored more than once.

To solve these problems, we can use the main features of json-api-normalizer, such as:

  • Merge data and included fields, normalizing the data.
  • Collections are converted into maps in a form of a id=> object.
  • The response’s original structure is stored in a special meta

First, in order to solve problems with redundant structures and circular dependencies, the introduction of the distinction of data and included data objects in the JSON API specification is needed. Second, there is a constant update on data in Redux, although gradually, that can help with the performance improvement.

 Now that you know why JSON API works best with Redux, it can be concluded that this approach can assist us in prototyping a lot faster and flexible with changes to the data model. If you are in doubt whether using Redux with JSON API or not, this article will help you find the solution and reason why you shouldn’t doubt this method.

The 4 Most Used Programming Languages

The-4-Most-Used-programming-languages_ywf

Nowadays, software developers are in high demand. This makes good developers are hard to find, yet they have the luxury of choosing from more than one job offer. So, what makes a ‘good developer’? A good developer should at least know some of the following skills. If you wish to become a good web developer, make sure you have mastered below skills.

  1. C#

C# is designed to be relatively easy and straightforward which makes it incredibly popular among developers and employers alike. C# is primarily used to develop web, mobile and enterprise applications while supporting imperative, functional and object-oriented paradigms.

Above all, there are two reasons why C# developers are terribly needed. First, it is because of its flexibility and usability. Second, it is firstly developed by Microsoft to build apps on the Microsoft platform.  So, it surely will fit in most common Microsoft IT infrastructure, which many companies have set in their system.

  1. PHP

PHP is another popular option; it’s an open source, server-side scripting language. In fact, PHP have powered millions of websites across the world, including high-profile sites such as Facebook and Wikipedia. Moreover, PHP is a language that is so popular that is used extensively in WordPress.

Over the years, PHP’s popularity has increased and there are no signs that this demand will slow down. That is why many companies will offer high salary for getting a good PHP talent.

  1. Java

Java is one of the oldest language programs that are favorable among developers. Because it is relatively easy and versatile, Java has become an attractive proposition for corporations and developers. Besides, it has many users, many existing applications and such a vast ecosystem.

Furthermore, Java is a stable language which makes the job market shows sustained hunger for developers in this field.

  1. JavaScript

Another language program that has gained everlasting popularity is JavaScript. It’s a versatile, object-orientated programming language that is built into most major browsers, including Firefox and Safari. Even though, JavaScript has been around for years but it can manage to hold its own against the existence of so many new languages. In fact, many regard it as one of the need –to-know language to help further a career. With so many developers have acquired this language, you need to double your work to stand out from the crowd.

3 JavaScript Libraries to Look Up for in 2017

3-javascript-libraries-to-look-up-for-in-2017

For some web developers, JavaScript’s ecosystem can be fatigue. Especially this year where there is a lot of tooling and configuring is required. So, to make your work easier, we submit a list of 3 generic libraries/frameworks for front-end development.

Vue.js

If you haven’t put any attention on Vue.js before, now you have to keep your eyes on. It is a tiny JavaScript framework which seems to primarily focus on views and give you only a handful of tools to regulate data for those views. Moreover, Vue.js is also good for a change as it doesn’t get stuffed with programming design pattern and limitations.

There are two types of Vue.js. A stand-alone version that includes the template compiler and the runtime version that doesn’t. You can see its simplicity, through an example of a component that shows a message and brings interactivity to a button to reverse the message.

<div id="app">
  <p>{{ message }}</p>
  <button v-on:click="reverseMessage">Reverse Message</button>
</div>
import Vue from 'vue'

new Vue({
  el: '#app',
  data: {
    message: 'Hello World!',
  },
  methods: {
    reverseMessage: function () {
      const reversedMessage = this.message
        .split('')
        .reverse()
        .join('');

      this.message = reversedMessage;
    },
  },
});

Don’t you worry about the existence of other plugins, as you still can find them on Vue.js. In fact, several guides are available to use there. This framework will be suitable for you, especially if you wish to have productive fast. It also scales well as the project grows.

Svelte

Svelte must be the latest JavaScript Libraries as it has been released in mid-November 2016. At some point, it may looks similar to Vue.js, but leaves a smaller footprint. “Traditional” frameworks need runtime code to define and execute modules; keeps state, update the views and do whatever frameworks do. Moreover, with Svelte you can dissolve into clean JavaScript code as of you didn’t use a framework at all. The big advantages that you can get is that its file size.

Svelte has plugins so you can compile the source code using Webpack, Browserify, Rollup or Gulp.

You can use the below example of creating the Vue.js example with Svelte as a comparison:

<p>{{ message }}</p>
<button on:click="reverseMessage()">Reverse Message</button>

<script>
export default {
  data () {
    return {
      message: 'Hello World!',
    }
  },
  methods: {
    reverseMessage () {
      const reversedMessage = this.get('message')
          .split('')
          .reverse()
          .join('');

      this.set({
        message: reversedMessage,
      });
    }
  }
};
</script>

The very same module created with Vue.js produces a 7kb bundle. Svelte produces a 2kb file.

In terms of performance, Svelte competes with Inferno. This makes Svelte becomes a good choice if you care about your application’s footprint. At the time of writing, Svelte either doesn’t have its plugin system documented, or doesn’t have one at all. The TODO indicates that Svelte will support plugins and might have an API to hook into the framework.

The compatibility of the compiled code depends on your build workflow stack, so it’s hard to say what its default compatibility is. Technically you should be able to achieve pre-ES% support by including ES5 shims.

To conditionally load and invoke modules, Conditioner.js is one of the good choices. The difference from other module loaders is that conditioner.js allows you define conditions under which to load and/or show a module. This results in reducing loading time and saving bandwidth.

However, you better already have functional components in place that are enhanced with a given JavaScript module. How those modules are defined is entirely up to you. You could even make it load modules from your favorite framework.

To get started, you can install it via npm: npm install conditioner-js.

The demo is unlike previous ones to better illustrate Conditioner.js’ features. Imagine we wish to show the time remaining to an event. A module is shown like this:

import moment from 'moment';

export default class RelativeTime {
  /**
   * Enhance given element to show relative time.
   * @param {HTMLElement} element - The element to enhance.
   */
  constructor(element) {
    this.startTime = moment(element.datetime);

    // Update every second
    setInterval(() => this.update(), 1000);
    this.update();
  }

  /**
   * Update displayed relative time.
   */
  update() {
    element.innerHTML = this.startDate.toNow();
  }
}

It is so simple to initialize the module:

<time datetime="2017-01-01" data-module="ui/RelativeTime">2017</time>

Conditioner will then load the ui/RelativeTime module at this location in the DOM. Note the content is already present and in an acceptable format and the module only enhances that.

If you want a module to initialize only when it’s visible to a user, you can do so with conditions:

<!-- Show RelativeTime only if it is visible to the user -->
<time datetime="2017-01-01" data-module="ui/RelativeTime" data-conditions="element:{visible}">2017</time>
<!-- Keep showing RelativeTime after it was visible to the user -->
<time datetime="2017-01-01" data-module="ui/RelativeTime" data-conditions="element:{was visible}">2017</time>

Conditioner.js has quite an extensive list of monitors, which you use to define conditions. Don’t fret! You only have to include those you need, preventing the inclusion of unnecessary code.

You can also pass along options as a JSON string or a slightly more readable JSON variant.

<!-- JSON variant -->
<div data-module="ui/RelativeTime" data-options='unit:"seconds"'>...</div>
<!-- Or good old JSON -->
<div data-module="ui/RelativeTime" data-options='{"unit":"seconds"}'>...</div>