Answer the question
In order to leave comments, you need to log in
How to use multiple variables in a store?
I tried to make a page that would have two counters that are controlled through ngrx. Each counter has its own variable in the store.
LIVE DEMO
I think my solution is redundant. Can you please tell me if there is a simpler and shorter way to implement the same functionality using ngrx?
Well, if you show this with a code example, I will be wildly grateful
Answer the question
In order to leave comments, you need to log in
The state will be an object containing the values of all counters:
const initialState = {
first: 0,
second: 0,
};
class CounterAction implements Action {
constructor(public type: ActionTypes, public payload: string) {}
}
function counterReducer(state = initialState, action: CounterAction) {
switch (action.type) {
case ActionTypes.Increment:
return {
...state,
[action.payload]: state[action.payload] + 1,
};
...
<div *ngFor="let item of count$ | async | keyvalue">
<button (click)="increment(item.key)">Increment</button>
<div>Current Count: {{ item.value }}</div>
<button (click)="decrement(item.key)">Decrement</button>
<button (click)="reset(item.key)">Reset Counter</button>
</div>
increment(key) {
this.store.dispatch(new CounterAction(ActionTypes.Increment, key));
}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question