Component Store support for ACTIONS #4220
-
Any guidance will be highly appreciated! :) |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
The reasons (including trade-offs and benefits) can be found on the webpage, https://ngrx.io/guide/component-store/comparison |
Beta Was this translation helpful? Give feedback.
-
While it may introduce a conflicting pattern, you can use global store actions and a reducer in a component store: const reducer = createReducer(
{ counter: 0 },
on(IncrementCounter, state => ({ counter: state.counter + 1 })),
on(DecrementCounter, state => ({ counter: state.counter + 1 }))
);
class MyComponentStore extends ComponentStore<State> {
private readonly actions$ = inject(Actions);
constructor() {
super(reducer.initialState)
}
applyReducer = this.effect(() => {
return this.actions$.pipe(
tap(action => this.setState(reducer(action, this.get())))
);
});
} |
Beta Was this translation helpful? Give feedback.
-
It is likely that you could model the problem differently for better results. Instead of updating a local variable in your component when an action occurs, you could instead update the global or component store state in reaction to that action, and then select and include that state in your component. |
Beta Was this translation helpful? Give feedback.
-
I figured out a case where in using actions in component store can cause an issue. @for (item of items) {
<app-item [item]=item></app-item>
} And the ChildComponent requires to have a store and get data of subItem using a service call. readonly getSubItem = this.componentStore.effect(() =>
this.actions$.pipe(
ofType(ItemActions.GET_SUBITEM),
mergeMap((action) => this.service.getSubItem(action.subItemId).pipe(
tapResponse(
(response) => {
const subItem: SubItem = plainToInstance(SubItem, response.data)
this.store.dispatch(ItemActions.GET_SUBITEM_SUCCESS({ subItem: subItem }));
this.reducers.subItem(subItem);
},
(error: HttpErrorResponse) => {
this.store.dispatch(ItemActions.GET_SUBITEM_ERROR({ error: error }));
throw error;
}
)
)
))) This effect would listen to any GET_SUBITEM action irrespective of the component that dispatched it. This would trigger the effects bound to each item component and the same service call would be made and same data would be reduced in each component's store. Everything would be everywhere. This happened because the actions are Global whereas the component stores are tightly bound to the life cycle of the component. And hence actions if used. should be used carefully with component store. |
Beta Was this translation helpful? Give feedback.
I figured out a case where in using actions in component store can cause an issue.
Consider the following scenario:
ParentComponent:
And the ChildComponent requires to have a store and get data of subItem using a service call.
We write effects listening to get action in the ChildComponent's component store as follows: