Redux ActionCreators

redux actionCreators

   

    An action is just a plain javascript object that describes what just happened. based on the type of action reducer just comes to know what properties it should update.

     Till now how we dispatched actions like ,

store.dispatch({         
         type:'USER_ADDED',         
      payload:{             
               id:1,             
             name:'webdev99'         
              }         
});

    we need to type the entire object structure to dispatch the action. what if there are multiple places where we want to dispatch the same action. then we have to repeat this entire object structure to dispatch the action.

    To improve this we can create a function that will create an action object for us & then we can use that function everywhere we require.

    we call this function action creator.

import * as actions from './actionTypes';
 function UserAdded(action){
          return {
                    type:actions.USER_ADDED,
                    payload:{
                             id:action.id,
                             name:
                            }
             }                                                                     
 } 

How to use this action creators:

 import {UserAdded} from './actionCreator';
 store.dispatch(UserAdded({id:1,name:'webdev99'})); 

    Because of action creators if tomorrow we want to change the action structure then we only need to make changes in the UserAdded function in actionCreator.js

Action creators using arrow function:

    We can create action creators using arrow function because they have more concise syntax

 import * as actions from './actionTypes';

 export const  UserAdded => action=>({
                    type:actions.USER_ADDED,
                    payload:{
                             id:action.id,
                             name:action.name
                            }                                               
         }) 

Leave a Reply