{{announcement.body}}
{{announcement.title}}

How to Use State Inside of an Effect Component With ngrx

DZone 's Guide to

How to Use State Inside of an Effect Component With ngrx

In this article, we discuss how to work with state inside of an effect component in Angular with ngrx.

· Web Dev Zone ·
Free Resource

For this post, I assume you already have knowledge about ngrx (a reactive state management framework for Angular), and you are working with reducers, actions, effects, and selector components. You can find information in ngrx. Today, I want to show you how to work with state inside of the effect component.

TypeScript


This is a very simple example of an effect. It's defined by the getInfoAction  action, and there is a call to service getInfo. Then, it's fired the action, getInfoSuccessfulAction. At this point, everything is straightforward, but what if you need to get some value from @ngrx/store. Well, the good news is you can do it; let me show you how to.

The idea is to inject a Storage instance into the Effect. Then, you can use it in your effect factory method. 

Then, you constructor looks like this:

TypeScript


Now, you can use your storage object to get data from your current state. (You can use a Selector.) I am going to show you my create effect method updated to use the Storage object.

TypeScript


  1. withLatestFrom : The method to use your selector.
  2.  getInfoName : The regular ngrx selector.
  3.  infoName : The value return by the selector (you can use it as a parameter on your call service).

In this way, you can use a value saved into your storage inside your effect. Now, I want to show you an example with more complexity. How you can use this approach when the action used by your effect has parameters. Do not worry about the solution. It's really easy.

This is the action definition with a parameter (A string parameter the parameter's name is greeting).

TypeScript


This is the effect definition using the greetingAction and a value (current user name) from Storage.

TypeScript



Further Reading

Topics:
angular 8 ,javascript ,ngrx ,redux ,tutorial ,typescript

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}