Best practices

The following files points to the demo project Chapter9/BestPractices.

So far, we have created some working code, but it could look a lot better, and be less error prone as well. There are steps we can take to improve the code, those are:

  • Get rid of so-called magic strings and rely on constants
  • Add a default state to your reducer
  • Create so-called action creators
  • Move everything into a dedicated module and split up it up into several components

Let's have a look at our first bullet point. Given the type of actions we perform on our jediList, we can create a constants.ts file for them, like so:

// jedi.constants.ts

export const ADD_JEDI = 'ADD_JEDI';
export const REMOVE_JEDI = "REMOVE_JEDI";
export const LOAD_JEDIS ="LOAD_JEDIS";

Now, when we refer to these actions we can instead import this file and use these constants instead, decreasing the risk of us mistyping.

The second thing we can do is to simplify the creation of actions by creating the so-called action creator. We are so far used to typing the following to create an action:

const action = { type: 'ADD_JEDI', payload: { id: 1, name: 'Yoda' } };

A better habit here is to create a function that does this for us. For the case with the list reducer, there are three possible actions that can take place, so let's put all these in a actions.ts file:

// jedi.actions.ts

import {
ADD_JEDI,
REMOVE_JEDI,
LOAD_JEDIS
}
from "./jedi.constants";

export const addJedi = (id, name) => ({ type: ADD_JEDI, payload: { id, name } });
export const removeJedi = (id) => ({ type: REMOVE_JEDI, payload:{ id } });
export const loadJedis = (jedis) => ({ type: LOAD_JEDIS, payload: jedis });

The point of creating the actions.ts file was so that we would have to write less code when we dispatch actions. Instead of writing the following:

store.dispatch({ type: 'ADD_JEDI', payload: { id: 3, name: 'Luke' } });

We can now write this as:

// example of how we can dispatch to store using an actions method

import { addJedi } from './jedi.actions';
store.dispatch(addJedi(3, 'Luke'));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.13.192