Introduction to Redux thunks
The word "thunk" is a programming term that means "a piece of code that does some delayed work". Rather than execute some logic now, we can write a function body or code that can be used to perform the work later.
It is good to let redux handle the asynchronous data fetching too. We traditionally were using redux-thunk and redux-saga. These two are redux middleware which listen to the dispatched actions and perform the asynchronous activities right within the redux flow.
The Thunk Code
const reduxThunkMiddleware = storeAPI => next => action => {
// If the "action" is actually a function instead...
if (typeof action === 'function') {
// then call the function and pass `dispatch` and `getState` as arguments
// Also, return whatever the thunk function returns
return action(storeAPI.dispatch, storeAPI.getState)
}
// Otherwise, it's a normal action - send it onwards
return next(action)
}