Search code examples
reactjsreact-reduxredux-thunk

where is dispatch coming from in this line? export const setAlert = (msg, alertType,timeout=5000) =>dispatch =>


I came across this code. He/she Is creating an action for redux in react-redux app. I don't understand where dispatch is coming from . Can you explain please also is this a good practice?

import uuid from 'uuid'; import {SET_ALERT,REMOVE_ALERT} from './types'; export const setAlert = (msg, alertType,timeout=5000) =>dispatch =>{ const id = uuid.v4(); dispatch ({ type:SET_ALERT, payload:{msg, alertType, id} }); setTimeout(()=>dispatch({type:REMOVE_ALERT,payload:id}),timeout)}


Solution

  • I guess it is using redux-thunk, which works as a middleware. setAlert returns the function, which is being called with the dispatch as first parameter of that function. It maybe helps more to understand if you clean it up a bit

    export const setAlert = (msg, alertType,timeout=5000) => {
        const id = uuid.v4();
    
        return (dispatch) => {
            dispatch ({
                type:SET_ALERT,
                payload:{
                    msg,
                    alertType,
                    id
                }
            }); 
        };
    

    I generally use it in cases I need to work with async functions inside an action, such as ajax requests.