How to Use State Inside of an Effect Component With ngrx
Join the DZone community and get the full member experience.
Join For FreeFor 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.
xxxxxxxxxx
@Injectable()
export class AppEffects {
constructor(private actions: Actions, private service: yourService) {}
infoEffect =
createEffect(() =>
this.actions.pipe(
ofType(getInfoAction),
mergeMap(() =>
this.service.getInfo()
.pipe(
map(resp => getInfoSuccessfulAction({info: resp,}))
)
)
)
);
}
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:
xxxxxxxxxx
constructor(private actions: Actions, private service: yourService, private store: Store<GameState>) {}
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.
xxxxxxxxxx
infoEffect =
createEffect(() =>
this.actions.pipe(
ofType(getInfoAction),
withLatestFrom(this.store.select(getInfoName)),
mergeMap((infoName) =>
this.service.getInfo(infoName)
.pipe(
map(resp => getInfoSuccessfulAction({info: resp,}))
)
)
)
);
withLatestFrom
: The method to use your selector.-
getInfoName
: The regular ngrx selector. -
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).
xxxxxxxxxx
export const greetingAction =
createAction('Greeting Action', props<{ greeting:String,
}>());
This is the effect definition using the greetingAction
and a value (current user name) from Storage
.
GreetingEffect =
createEffect(() =>
this.actions.pipe(
ofType(greetingAction),
withLatestFrom(this.store.select(getUserName)),
mergeMap(([greetingText,userName]) =>
this.service.sayHello(greetingText,userName)
.pipe(
map(resp => greetingActionSuccessfulAction({greeting: resp,}))
)
)
)
);
Further Reading
Opinions expressed by DZone contributors are their own.
Comments