Search code examples
reactjsreduxredux-thunk

Redux / Calling dispatch from an action


How can I dispatch an action inside from an action without passing it from the initial call? I just want to remove the props.dispatch but I'm not able to get it work. Already using redux-thunk and I'm new to react. My version works, but it's not the best, I guess.

<Files
    onDrop={file => {
        props.dispatch(addFile(props.dispatch, {id: uuidv4(), file}));
    }}
/>

actions.js:

// addFile
export function addFile(
    dispatch,
    {
        id = uuidv4(),
        file = [],
    } = {}
) {
    doSomething(dispatch, id);
    return {
        type: 'ADD_FILE',
        payload: {
            id,
            file,
        },
    };
}

// doSomething
function doSomething(dispatch, id) {
    dispatch(callOtherAction(id));
}

Solution

  • You can use mapDispatchToProps and pass it as the second parameter to the connect method. Then you will have dispatch method along with your props.

    should look something like this:

    const mapDispathToProps = dispatch => ({
        addFileAction: (file) => addFile(dispatch, file)
    })
    export default connect(null, mapDispathToProps)(Component);
    

    Your addFile action can now pass the dispatch to other actions as well.