The following scenario can be found in the code repository under Chapter9/DemoEffects.
This sounds a bit cryptic, so let's take a realistic scenario. You want to fetch products using AJAX from an endpoint. If you think about what you are about to undertake in the following steps:
- Dispatch a FETCHING_PRODUCTS, this sets up our state so we can see that an AJAX request is under way and we can thereby use this to display a spinner for as long as the AJAX request is waiting to complete.
- Perform an AJAX call and retrieve your products.
- If successfully retrieving the products, then dispatch FETCHING_PRODUCTS_SUCCESSFULLY.
- If there is an error, then dispatch FETCHING_PRODUCTS_ERROR.
Let's solve this task in the following steps:
- Create a reducer for it.
- Create actions and action creators.
- Create an effect.
- Register the preceding effect with our effects module.
To perform all of this, we will create a feature module. To do so, we create the product/ directory with the following files:
- product.component.ts
- product.actions.ts
- product.constants.ts
- product.reducer.ts
- product.selectors.ts
- product.module.ts
- product.effect.ts
All of these files are known to us before, except for product.effect.ts.