Why side effect?
Because ngrx says your reducer should be pure function, you can not use API asynchronous call in reducer.
What your reducer does? -> it update your state and return updated state.
So how you can make API in reducer? -> To achieve this, ngrx provide effect in @ngrx/effect.
Like reducer has switch case to identified action so effect will also subscribe all action and it will listen all actions.
How Effect will identified action? -->
like in reducer -
export function reducer(state = initialState, action: myActions.Actions) {
switch (action.type) {
case myActions.actionType.SEND_CANDIDATE_OTP: {
return Object.assign({}, state, {otp:'test'});
}
}
Effect will look like ->
export class CandidateEffect {
@Effect()
sendCandidateOTP$: Observable<Action> = this.action$
.ofType(myActions.actionType.SEND_CANDIDATE_OTP)
.pipe(
switchMap((action: myActions.GetCandidateAction) => {
const input: myModel.GetCandidateInput = action.payload;
return this.candidateService.SendCandidateOTP(input).pipe(
map(resp => {
return new myActions.SendCandidateOTPSuccessAction(resp);
}),
catchError((err, caught) => {
return of(new myActions.SendCandidateOTPFailAction(err));
})
);
})
);
}
In the above piece of code you will identified action using typeOf keyword from ngrx.