Adding Redux to an Ionic Application

Redux.
You certainly have heard this word unless you lived in a cave during the past four years, if that’s the case welcome back, Donald Trump is president of the United States and World War 3 is coming soon (here is a secure source ūü§£).

redux in ionic app intro trump

Yep, this guy.

Joke aside.
Redux is rampaging because it allows us to write better quality applications and debug them easily.We, Ionic developers, are used to Angular bindings, modifying our properties in our Typescript Classes and having an application that evolves constantly.

With Redux a Store is available and contains the State of the application. An Action will be dispatched and go through a Reducer that will consider the current State to create a new State. This method prevents side effects by using pure functions that create new State objects, instead of mutating the previous State.

It can seem frightening, but it’s as simple as this:
redux in ionic app intro simplificationBy the end of this tutorial, (I hope) you will be amazed by Redux’s power.

Warm Up

As usual, we start by setting up our Ionic project:

Some very important plugins:

  1. redux and @angular-redux/store: The core plugins for using Redux
  2. flux-standard-action: Will help us properly define our Redux Actions
  3. redux-logger: Will give us more information as we access our Store

This application will be very simple. We will allow the user to create some colored squares and remove the last square in our array.

Which leads us to the home.html file:

Let’s start with the easy elements.

The buttons will trigger the addColors and removeLastColor methods located in the home.ts file.

The ngFor can be surprising here:

  1. The “$” symbol at the end of the colorList$ property: This is a classic notation for Observables. We are not working with Angular bindings here, but using an RxJS Observable. When the colorList evolves in the Redux Store, the information will be updated on the UI
  2. Since we are working with an Observable, the async Pipe is required otherwise the ngFor Directive won’t work. The async Pipe is a god Pipe when working with Redux so keep it mind

A new div will be created for each color inside the colorList$ property. This div will show a 100x100px square and use the color value as backgroundColor.

We can now dive in the TypeScript code.

We will create the color folder, which will contain:

  1. color.model.ts: Structure our data
  2. color.action.ts: Actions to dispatch on our Store
  3. color.reducer.ts:  Creating the next State according to the incoming Action (basically just a switch case)

Let’s start with the easiest one, the color.model.ts file:

It’s preferable to be as strict as possible so our dear Visual Studio can help us (it’s great to have a warning when we try to insert a tomato in an usb port).
The States inside our Redux Store will be modeled as the ColorListState Interface. They will have a¬†colorList property that will be an array of string (ex: [‘red’, ‘blue’, ‘pink’]).

Only one action will have a payload: adding new colors.
The ColorAddPayload will be an array of new colors to add.
The MetaData only gives more information on how the data are structured.

We can now move to the Redux Actions!

Redux Actions

With the color.action.ts initialization:

The dispatch import here is a Decorator, just like @Component, @dispatch later on will transform our methods into dispatchable Redux Actions.

FluxStandardAction helps us create standardized Redux Actions.
The last imports are ColorAddPayload and ColorAddMetaData from the previous color.model file.

We can now declare some new Action types by taking the FluxStandardAction as example.
The ColorAddAction type is the only one that will have specific types for the payload and the metadata.

Finally we start our ColorActions Service. Nothing fancy, just some constants to uniformize our Redux Actions calls in the application.

Here are our actions:

They are all defined by:

  1. A type
  2. Some metadata
  3. The payload

Very simple here, all of them return a ColorAction, they are like a restaurant’s menu. Once again,¬†addColors is the only action that will pass some payload information: the colors that the method will receive when we call the Action.

And that’s it for the Redux Actions!

Moving on to the Reducer.

Reducer

Here is the initialization of the color.reducer.ts file:

The imports are only there to add some typings to our data.
An INITIAL_STATE value is used as default ColorListState.
The colorReducer is just an exported function. It will work with the current ColorListState and a Redux Action, in the end it returns a new ColorListState.

As I stated before, a Reducer is just a simple switch case:

It will look at the action’s type and act accordingly.

The most important part here is that a Reducer is a pure function. It will work with the data that are passed (state, action) and return a result without modifying anything else.

There won’t be any external interactions:

  1. No external data acquisitions: The reducer won’t make a call to a database or use the local storage, etc.
  2. No external data modifications: The reducer won’t modify a database or make some requests to a server, etc.

We have to be careful here by avoid modifying the state that we receive. It’s better here to use functions that don’t modify the objects (immutability concept).
Here is an awesome post showing how to do this for arrays.

Ok back to the cases.

Loading:

Here we just return a new object with some colors in the colorList property, nothing fancy.

Adding:

We change our action’s type to ColorAddAction in order to properly acquire its payload.
The colorList property is built by creating a new array. The spread operator helps us merge the current state’s colorList and the payload array of colors received from the action.

Removing the last color:

The slice method is directly used on the current state’s colorList property. Don’t be afraid, this method won’t modify the object!
We take every colors except the last one.

And we are done!

The Final Touch

All we need now is setting up our app.module.ts and the home.ts files:

The¬†NgReduxModule is Angular’s Redux core module, without this, our Ionic application won’t understand anything related to Redux.
The ColorActions Class is added as a Provider to use it later in the HomePage‘s method for triggering the Redux Actions.
Finally the¬†DevToolsExtension is another Service that you will love (trust me ūüėČ).

Our last step: the HomePage.

Subscribe to my mailing list to get access to a Free 7-day Ionic 3 introduction email course!
100% Privacy. I'll never spam you!

Import wise it’s quite packed:

Almost everything we created are imported there (ColorListState, ColorActions, etc.).
The novelty here is the select Decorator, it allows us to select a property from the current state in our store.

Observable is only imported here for typing purpose.
Finally the reduxLogger is required here instead of imported.

Now the good stuff:

Thanks to the @select Decorator the colorList property is acquired as a readonly information.
This Decorator is very powerful and we will see more of it in the next tutorial¬†ūüėČ.
The Redux store, colorActions Service and devTools Service are finally injected (about time right?).

Our precious store can now be configured.
The first parameter is the colorReducer, followed by the INITIAL_STATE, our logger initialization and finally the¬†devTools enhancer if it’s enabled.
Once the Redux store is configured, we can load our colors by triggering the loadColors method from the colorActions property.

Launching our Ionic application:

We got our beautiful squares:

redux in ionic app intro loadThat’s a good start!
Thanks to the redux-logger library we have some nice logs:

redux in ionic app intro load loggerThe colorList is now populated after the LOAD_COLORS action.

Back to the home.ts file to add our final methods:

We only use the colorActions property’s methods and that’s it!

Here is the final result:

redux in ionic app result

Ok we have our squares, with our Actions-Reducers-Model set, but what the **** do we benefit from here?
By using this system, we have predictability and consistency which opens the door to new usage.

This Should Blow Your Mind

I only need one browser extension to blow your mind. It’s available there.
The Redux Devtools Extension.

Everything related to the Redux store is available there:

redux in ionic app intro devtoolIonic developers generally debug their applications by using console.log or breakpoints. Putting them at places, reloading the application, checking the value of a property, adding some logs at other places, reloading, etc. This can take some time because WebPack has to compile the TypeScript files, compress them, etc.

The Devtool is extremely powerful there. The whole history is available.

We can replay the actions:

redux in ionic app intro action replaySee the evolution of the states:

redux in ionic app intro state replay

Or the differences after an action:

redux in ionic app intro replay diffYou can also:

  1. trigger new actions
  2. use the tests that the Devtool wrote for each action
  3. save your state to a JSON file, send it by email to your colleague so he can import it in his Java, NodeJS, or C++ application (remember this time when a bug appeared but it was impossible to reproduce and you didn’t want to press the reload button?)
BONUS CONTENT
Enter your email address in the box below to get access to this tutorial (and others) source code.

Conclusion

We are generally used to creating our Ionic apps with our bindings. Redux philosophy moves the application’s State into a Store that gets updated by dispatchable Actions. Those Actions will reach some Reducers and create new States.
Since everything is predictable, it’s easier to track the evolution of the application and work around it instead of presuming how things should go.
This simplify the creation of more complex systems. The Devtool is one of them.
In the next tutorial we will see how we can easily add the time travel feature in our application so the user can undo and redo its Actions, moving from one State to another.

No Comments Yet

Leave a Reply

Your email address will not be published. Required fields are marked *

4 Shares