Learn Redux in 5 mins

Published May 03, 2018Last updated May 20, 2018
Learn Redux in 5 mins

Redux is a library/design pattern that helps divide your application into a logic and view layer. In a Redux application, there is only a single immutable store and a single way to update the store (single source of truth).

We will cover the process of using Redux in your JavaScript apps below.

Folder Structure:
--dataContainer
---actions
---reducers

Create a way to update your store:

To achieve this, we need to do two things.

First, we need to create our action creator, and second, we need to create our reducer.

Creating an action creator
An action creator is a function that returns an action. An action is an object with a type property and a payload property. An example of an action is:

{
   type:'LOGIN',
   payload:payload
}

Now, let’s create our action creator like so.

const identify_user=(firstName,lastName)=>{
  const fullname=`${firstName} ${lastName}`

return{
    		type:'IDENTIFYING_USER',
    		payload:fullname
}
}

This is what a typical action creator looks like. You may perform operations within your action creator and then return your action.

Here is another instance of an action creator with an action taking a promise as a payload. Now this is the trick: know this, your action creator will first dispatch IDENTIFYING_USER_PENDING just before the promise is triggered, then dispatch IDENTIFYING_USER_FULFILLED if the promise has been resolved or IDENTIFYING_USER_REJECTED if the promise has been rejected. Go to your actions folder, create a file, name it ‘authAction.js’ and do the following:

export const identify_user=(email,password)=>({
    type:'IDENTIFYING_USER',
    payload:axios.post(“https://mybaseurl/signin”,{email,password})
})

Now, this only works with redux-promise-middleware installed. I personally recommend it , because it saves me many lines of code.

Creating a reducer
A reducer is a pure function that receives an action as an argument and updates the store.

A typical reducer will look like this:

const initialstate={
    user:{} 
}
const identifyUser=(state=initialstate,action)=>{
    switch(action.type){
        case'IDENTIFYING_USER':{
            return{ ...state, 
              user: action.payload   }
            
        } 
        default:{
            return{...state}
        }

}

Please notice how the case IDENTIFYING_USER in the code above matches the type property of the action we discussed earlier. This is how Redux determines what part of the store to update.

Here is another instance of a reducer, listening for three events: IDENTIFYING_USER_PENDING, IDENTIFYING_USER_FULFILLED, and IDENTIFYING_USER_REJECTED. Now, go to your reducer folder, create a file, name it ‘authReducer.js’ and do this:

const initialstate={
    fetching:false, user:{}, error:null 
}
const identifyUser=(state=initialstate,action)=>{
    switch(action.type){
        case'IDENTIFYING_USER_PENDING':{
            return{ ...state,
                    fetching:true,
                    user:{}, 
              error:null   }
            
        }
 case'IDENTIFYING_USER_FULFILLED':{
            return{ ...state,
                    fetching:false,
                    user:action.payload,
                    }
            
        }
        case'IDENTIFYING_USER_REJECTED':{
            return{ ...state,
                    fetching:false,
                    error:action.payload    }
            
        }
        default:{
            return{...state}
        }
}

Export default identifyUser
 

Next, we create another file in our reducer folder and name it ‘index.js’. This is where we’ll create our combine reducers, a method that generates a function that calls our reducers with the slices of store selected.

import {combineReducers} from 'redux'
import authReducer from  './authReducer'

export default combineReducers({
    auth: authReducer
        });

Please notice we imported our authReducer and used it when creating our combine reducers.

Creating your store:

First, install the following dependencies, like so:

npm install redux
npm install redux-promise-middleware
npm install redux-thunk
npm install redux-logger

Dependencies:
redux- This is the core dependency required to use Redux.
redux-promise-middleware – This module enables promises to run in our actions.
redux-thunk – This module enables us to use asynchronous functions in our action creator.
redux-logger- This module logs the store on the console whenever an action is fired. This is very useful for debugging.

Then, we’d go to the root of our ”dataContainer” folder, create a file, and name it “store.js”, and enter the following:

import {applyMiddleware,createStore} from 'redux'
import reducers from'./reducers/index'
import promise from 'redux-promise-middleware'
import thunk from 'redux-thunk'
import logger from 'redux-logger'

const middleware = applyMiddleware(promise(),thunk,logger)

const store = createStore(reducers,middleware)

export default store;

Notice that we imported our combine reducers on line 2 of the above code, along with the middlewares we will be using.
On the last line, we exported our store.
That's it, our store is ready. Thank you for reading this article.

In the next chapter, we’ll see the different ways we can dispatch actions in our React application.

Discover and read more posts from John Anisere
get started