Class 38: Remote APIs - mwilkin-401-advanced-javascript/bend-javascript-401d2 GitHub Wiki
Reaching out to a remote API is an asynchronous process, as it takes a certain amount of time between when the call to the API is initiated or sent and when a response is received.
Therefore, it is important to consider this asynchronicity when utilizing Redux in a React application.
Actions:
- When hitting an API, a change in state is necessary, when the call is initiated, when the response is received and if the request failed.
- This is achieved by dispatching actions which are processed by reducers in a synchronous manner.
Three synchronous actions are needed:
- An action informing the reducers that the request began
- An action informing the reducers that the request finished successfully.
- An action informing the reducers that the request failed.
It is important to remember that reducers are just functions.
Asynchronous actions and Thunk
- The role of this middleware is very simple: verify if an action is a function and in which case execute it. As a consequence, actions can be created as functions rather than simple objects.
Redux Thunk elegantly solves the problem of managing asynchronous actions in Redux. Unlike the reducer, middleware is not required to be a pure function, so the thunk middleware can perform functions that trigger side effects without any problem.
While easy to implement, it forces you to alter the original nature of an action creator by making it more complicated by sending the HTTP request and handling the response. So in some instances, custom middleware might be more appropriate as it can be much more scalable and maintainable.