Z
Z
zlodiak2019-06-12 13:48:19
Angular
zlodiak, 2019-06-12 13:48:19

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

1 answer(s)
0
0xD34F, 2019-06-12
@zlodiak

The state will be an object containing the values ​​of all counters:

const initialState = {
  first: 0,
  second: 0,
};

One action is enough, in addition to the type, the name of the counter will be indicated:
class CounterAction implements Action {
  constructor(public type: ActionTypes, public payload: string) {}
}

Accordingly, we pass CounterAction to the reducer, and update the specified counter:
function counterReducer(state = initialState, action: CounterAction) {
  switch (action.type) {
    case ActionTypes.Increment:
      return {
        ...state,
        [action.payload]: state[action.payload] + 1,
      };
  ...

Next, let's show the counters in the component:
<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>

Well, let's ask them to update:
increment(key) {
  this.store.dispatch(new CounterAction(ActionTypes.Increment, key));
}
...

https://stackblitz.com/edit/angular-ms9wfw?file=sr...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question