How do NgRx Effects let you handle asynchronous operations, like an API call, in response to a dispatched action?
Short answer
An Effect listens for a specific action, performs an asynchronous operation like an HTTP request, and then dispatches a new action once that operation completes, keeping asynchronous side effects cleanly separated from the pure, synchronous reducer functions that update the…
Advertisement
AModel answer
An Effect listens for a specific action, performs an asynchronous operation like an HTTP request, and then dispatches a new action once that operation completes, keeping asynchronous side effects cleanly separated from the pure, synchronous reducer functions that update the actual state.
loadUsers$ = createEffect(() =>
this.actions$.pipe(
ofType(loadUsers),
mergeMap(() => this.userService.getUsers().pipe(
map((users) => loadUsersSuccess({ users })),
catchError((error) => of(loadUsersFailure({ error })))
))
)
);Real-world example
A user management page dispatches a loadUsers action, triggering an Effect that fetches the actual data from the server and dispatches a success action with the results, keeping the reducer itself completely free of any asynchronous logic.
Likely follow-ups
- Why must reducers stay pure and free of side effects like API calls?
- What is the difference between mergeMap and switchMap when used inside an effect?
Related topics