difference between return and dispatch in actions: Redux difference between return and dispatch in actions: Redux reactjs reactjs

difference between return and dispatch in actions: Redux


I am quite surprised nobody has come up with a definite answer. This comes really late but I will post this for people having the same question using redux-thunk as an example.As per the docs:

there is just one important thing you need to know: by using this specific middleware, an action creator can return a function instead of an action object. This way, the action creator becomes a thunk

The function returned receives the dispatch method as an argument, which you should use to trigger state updates, since the function by itself cannot dispatch actions event if you return an object. For example:

const getEvents = () => {  return async (dispatch) => {    const res = await fetch(        'https://someendpoint/events'    );    const events = await res.json();    return { // <-- this will NOT be sent to any reducer        type: GET_EVENTS,        events: [],    };   dispatch({ // <-- this will         type: GET_EVENTS,        events,    }); };

};

The section on Async Action creators explains this in more detail.


dispatch is a function of the Redux store. You call store.dispatch to dispatch an action. This is the only way to trigger a state change.

For more details, please refer to https://react-redux.js.org/using-react-redux/connect-mapdispatch