Search code examples
javascriptangularngrxngrx-store

why counter value increment and decrement only first time?


https://stackblitz.com/edit/angular-q8nsfz?file=src%2Fapp%2Fapp.component.ts

import {Component, OnInit} from '@angular/core';
import {Store} from '@ngrx/store';
import {Observable} from 'rxjs';

import * as fromApp from './app.store';
import {DecrementCounter, IncrementCounter} from './store/counter.action';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  c: Observable<object>;

  constructor(private store: Store<fromApp.AppState>) {
  }

  incrementCounter() {
     this.store.dispatch(new IncrementCounter());
  }

  decrementCounter() {
    this.store.dispatch(new DecrementCounter());
  }
  ngOnInit(){
    this.c =this.store.select('counterValue');

  }
}

Hi

can you please tell me why my counter value increment and decrement only first time .I have two button increment and decrement the counter value change on button click .but my value change only first time .it show 0 initial value which is correct but after that it don't work why ?


Solution

  • Replace initialState.counter + 1 to state.counter + 1;
    
      switch (action.type) {
        case CounterActions.INCREMENT:
          const counter = state.counter + 1;
          return {...state, counter};
        case CounterActions.DECREMENT:
          const currentCounter = state.counter - 1;
          return {...state, counter: currentCounter};
        default :
          return state;
      }