When my component inits, I want to dispatch an action to create the "campaignDraft" object. If the "CampaignOverview" exists, I need to make "campaignDraft" the same, if not exist, make it a preset object {a: 1} e.g.
The problem is that I'm trying to achieve this with Effects, but all my actions lead to browser freezes.
// component.ts
ngOnInit(): void {
this.store.dispatch(getCampaignDraft());
this.campaignFormSubscription = this.store
.pipe(select(selectCampaignDraft))
.subscribe((campaignDraft: CampaignModel) => {
this.campaignForm.patchValue(campaignDraft, { emitEvent: false });
});
}
// actions
export const getCampaignDraft = createAction(CampaignDraftActionTypes.GET_CAMPAIGN_DRAFT);
// effects
getCampaignDraft$ = createEffect(() => {
return this.actions$.pipe(
ofType(fromCampaignDraftActions.getCampaignDraft),
switchMap((action) => withLatestFrom(this.store.pipe(select(selectCampaignOnly)))),
map((campaign) => fromCampaignDraftActions.createCampaignDraft({ campaign: {a: 1} }))
);
});
// reducer
on(campaignDraftActions.createCampaignDraft, (state, { campaign }) => {
return {
...campaign,
};
}),
I do not know how to check the Store in effect - does "campaignOverview" exist or not to dispatch another action with this object or the preset one, help please.
we can use withLatestFrom as operator rather than returning it with switchmap, something like below
getCampaignDraft$ = createEffect(() => {
return this.actions$.pipe(
ofType(fromCampaignDraftActions.getCampaignDraft),
withLatestFrom(this.store.pipe(select(selectCampaignOnly))),
map(([action, campaign]: [ActionType, CampaginStateSliceType]) => {
if (exists) {
return A_Action();
} else {
return B_Action();
}
})
);
})