Binding action creators to the dispatch method

Actions creators are just functions that generate action objects which can later be used to dispatch actions using the dispatch method. Take for example the following code:

const TYPES = { 
    ADD_ITEM: 'ADD_ITEM', 
    REMOVE_ITEM: 'REMOVE_ITEM', 
} 
const actions = { 
    addItem: (name, description) => ({ 
        type: TYPES.ADD_ITEM, 
        payload: { name, description }, 
    }), 
    removeItem: (id) => ({ 
        type: TYPES.REMOVE_ITEM, 
        payload: { id }, 
    }) 
} 
module.exports = actions 

Later, somewhere in your application, you can dispatch these actions using the dispatch method:

dispatch(actions.addItem('Little Box', 'Cats')) 
dispatch(actions.removeItem(123)) 

However, as you can see, calling the dispatch method every time seems like a repeated and unnecessary step. You could simply wrap the action creators around the dispatch function itself like this:

const actions = { 
    addItem: (name, description) => dispatch({ 
        type: TYPES.ADD_ITEM, 
        payload: { name, description }, 
    }), 
    removeItem: (id) => dispatch({ 
        type: TYPES.REMOVE_ITEM, 
        payload: { id }, 
    }) 
} 
module.exports = actions 

Even though this seems like a good solution, there is a problem. It means, you would need to create the store first, then define your action creators binding them to the dispatch method. In addition, it would be difficult to maintain the action creators in a separate file since they depend on the dispatch method to be present. There is a solution provided by the Redux module, a helper method called bindActionCreators which accepts two arguments. The first argument is an object with keys, which represent the name of an action creator, and values, which represent a function that returns an action. The second argument is expected to be the dispatch function:

bindActionCreators(actionCreators, dispatchMethod) 

This helper method will map all the action creators to the dispatch method. For instance, we could re-write the previous example as the following:

const store = createStore(reducer) 
const originalActions = require('./actions') 
const actions = bindActionCreators( 
    originalActions, 
    store.dispatch, 
) 

Then, later somewhere in your application, you can call these methods without wrapping them around the dispatch method:

actions.addItem('Little Box', 'Cats') 
actions.removeItem(123) 

As you can see, our bound action creators look more like regular functions now. In fact, by destructuring the actions object, you can use only the methods you need. For instance:

const { 
    addItem, 
    removeItem, 
} = bindActionCreators( 
    originalActions,  
    store.dispatch, 
) 

Then, you can call them like this:

addItem('Little Box', 'Cats') 
removeItem(123) 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.156.50