Reputation: 1002
I have noticed that sometimes actions in Redux use return
and others dispatch
. I also noticed that dispatch
is used when there is some async operation in that action function, like reading/posting from/to a database, but I don't understand why. Could anyone shed some light on the crucial difference. Why don't we use dispatch
all the time for example, as in context API in React?
EDIT: I will add an example, that doesn't deal with the backend, so there is no async
await
cycle:
//with return
export const addLog = (log) => {
return{
type: ADD_LOG,
payload: log
}
}
//with dispatch
export const addLog = (log) => disptach => {
dispatch{
type: ADD_LOG,
payload: log
}
}
What's the difference between the two?
Upvotes: 8
Views: 2510
Reputation: 424
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.
Upvotes: 3
Reputation: 657
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
Upvotes: -1