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...