Run
git checkout third-step
before continuing to read.
As we saw in the previous step (Migrate local state in Redux
), Redux is a toolbox that comes with a lifecycle that allow you to separate each part of the application according to its concerns (SOC).
Currently, we can see in our little app two main parts:
- Our view, located in the
Component
folder - The state of our application, with methods (reducers & selectors) to interact with it, located in the
State
folder
But if we look into the Animes
component, we can see that the View part is communicates directly with an external part of our application: a rest API.
The response of the API cannot be predicted, because many external side effects can occur :
- Server error
- Poor network quality
- ...
According to the Separation Of Concerns, we want the View to handle ONLY user interface and user interactions.
We will therefore create a new part in our application to manage all communications with an external element (browser, localstorage, HTTP requests, ...): the Effect part.
In the figure below, you can see that the diagram previously seen in the second step has evolved:
Figure 2: Redux
lifecycle with middleware management (source: Redux. From twitter hype to production)
Redux allows the use of addons which are called middleware. According to the official documentation:
Redux middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.
Thanks to this powerful feature, we can imagine using it to create custom logging, or communicate with an external API.
Redux-Saga
is a Redux
middleware that allows us to manage asynchronous calls with a clear and simple API (called effects), and to organize them in sequences (called sagas).
Effects are functions provided by the library that introduce useful functionalities:
- Parallelization
- Race between calls
- Cancelling process
- ...
Sagas use a declarative syntax based on ES6 generators, so all effects will be yield
.
Generators make it easy to test sagas, step by step, without any mock.
I really recommend you to consult the documentation which is very complete.
- Install & configure
redux-saga
as explain in the documentation - Create your first saga and remove api call in
src/Component/Animes.js
You can see an example on https://redux-saga.js.org/ landing page.