AngularJs 1.7 with redux

When we build application in AngularJs we use component-based architecture. Once application starts to grow, we add module after module and feature after feature, and we create more and more services and controllers for each view. In such case requirement comes where controllers depends on multiple services and soon code become messy and hard to manage.
Syncing state between different controllers gets painful. We start depending on broadcasts to tell other controllers when to update their states. And then we decided to use Redux.

What is Redux?

According to the Redux official documentation, it is “a predictable state container for javascript apps”. Redux makes it easy to manage the state of your application. Another way of looking at this – it helps you manage the data you display and how you respond to user actions.

Redux may be kinda hard to wrap your head around at first, what it does is just helping you deal with states in JS. So What is state? You can think application having an initial state and all the following actions are just modifying that state.

Redux can be explained through following:

  • Actions
    >Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.
    Actions are plain JavaScript objects. Actions must have a type property that indicates the type of action being performed.
    {
      type: ADD_TODO,
      text: 'Build my first Redux app'
    }
    
  • Reducer
    Reducers specify how the application’s state changes in response to actions sent to the store.
  • Store
    The Store is the object that Holds application state, Allows access to state via getState(); ,Allows state to be updated via dispatch(action);, Registers listeners via subscribe(listener);, Handles unregistering of listeners via the function returned by subscribe(listener);
  • View Views are nothing but the component for an application.

so…

  • The whole state of your app is stored in an object tree inside a single store.
  • The only way to change the state tree is to emit an action, an object describing what happened.
  • To specify how the actions transform the state tree, you write pure reducers.

Starting our project

For implementing the redux store to our angular application we will use a great helper service called angular-redux.
It contains everything needed to handle state in Angular.

$ npm install ng-redux --save

Our entire code reside in client/app. The new folders introduced when using redux are : reducers, actions, constants and middlewares.
Reducers which will manage our state. Reducers are the only ones who can manipulate the state. They are executed after dispatching an action and, based on passed action type, change the state and return new one. To change state our components sends the action, actions are simply contains the payloads we want to pass to the store. so each action should have type and payload properties. To perform async requests we use middlewares as reducers are always synchronous. As the application will grow we will use many actions, so it is good approach to declared those in constant and use them when needed.

So lets start with creating blogs.js in constants folder, which will be constants of actions.

Now create our first store. For that we will create index.js in reducer folder.

combineReducers Is an helper function from redux allowing to construct our single store from multiple state objects.

Now lets create BlogsReducer for that we will create blogs.reducer.js in reducer folder.

In this blog reducer we are creating initial state. So when the app loads it will use this state object as default.
It added Blog and remove blog form state. It always returns the new state object. Here one thing to note is that we should always return new state object and never mutate the app state.

Now lets create actions creator, in actions folder with file name blog.actions.js

Here we are exporting 2 functions. Our component controller will interact with the state using those functions.

Now open app.js

So after importing ng-redux model we will register our RootReducer with the angular application using $ngReduxProvider.createStoreWith(RootReducer); . We can also pass a second argument to the createStoreWith that will hold an array of the middlewares functions as described in the previous section.

Open containers/home/home.html.

Once it is done let’s implement the controller methods containers/home/home.controller.js

Here connect function our controller to subscribe to the state changes. mapStateToThis

this.unsubscribe = $ngRedux.connect(this.mapStateToThis, BlogActions)(this);

allows us to select specific part of the state and bind it to our controller.
 mapStateToThis(state) {
      return {
          blogs: state.blogs
      };
  }

When the $scope is destroyed, we are using angular component hook to unsubscribe the state watcher.

$onDestroy(){
  this.unsubscribe();
}

Now let’s start our application

$ gulp

Now check http://localhost:3000/
Output:

Summary

You can use Redux with any frontend JavaScript library or framework. It helps with state management for all kind of JavaScript applications. Dan Abramov built Redux to make working with React better. The tooling and the community started around React. But, the library itself is not limited to React and is now used with a wide array of frontend frameworks. Redux has got nothing to do with application speed. It makes your application state easier to manage. There are lot of tutorials about using redux with angular. I hope this article will help you with setting up your angular & redux projects.

References:
A Beginners Guide to Redux
Redux
Angularjs with redux
ng-redux



Leave a Reply