I am struggling to wrap my head around the syntax/ understanding how the thunk function flow...
i.e. the following function:
function incrementAsync() {
return dispatch => {
setTimeout(() => {
dispatch(increment());
}, 1000);
};
}
I think I mostly am confused by the passing in dispatch
as an argument part. What exactly happens when incrementAsync
is called?
A normal Redux action is a plain JS object, as illustrated in the tutorial: https://redux.js.org/basics/actions
What Thunk does is to extend Redux so that actions can also be a function. When incrementAsync
is called, it returns a new function that takes an argument dispatch
. That function is then called by Redux (via Thunk), passing in the dispatch()
function from Redux as an argument, enabling you to dispatch more actions (a)synchronously.
This is all taking advantage of the fact that JS functions are first-class members of the language and can be assigned to a variable, and passed around.