Search code examples
angularngrxngrx-storengrx-effectsangular-ngrx-data

how to pass custom value in ngrx


this is .ts file where addValue() got error as : Expected 0 arguments, but got 1


  value: any
  name: string = ''

  constructor(private store: Store<{ counter: CounterState }>) {

  }
  ngOnInit() {

    // this.store.select(getCounter).subscribe(data=> {

    //   console.log("counter observable is called");
    //   // this.name = data
    // })

    //  ********** alternavtive to subsctibe is obersvable 

  }
  addValue() {
    console.log(this.value);
    this.store.dispatch(customIncreament({value: this.value}))

  }

I have tried above example in my new project. I have check lot of examples on internet to resolve the problem but nothing is worked with it. I think there is more things needs to add which I have missed with my code

.actions file

import { createAction, props } from "@ngrx/store";
import { CounterState } from "./counter.state";

export const increment = createAction('increment');
export const decrement = createAction('decrement');
export const reset = createAction('reset');

// creating the action for custome value to be used in counter
export const customIncreament = createAction(
    'customIncreament', props<{counter:number}>);

.reducer

import { state } from "@angular/animations";
import { createReducer, on } from "@ngrx/store";
import { changeNameAction, customIncreament, decrement, increment, reset } from "./counter.actions";
import { inititalState } from "./counter.state";

const _counterReducer = createReducer(inititalState,
    on(increment, (state: any) => {
        return {
            ...state,
            counter: state.counter + 1,
        };
    }),
    on(decrement, (state: any) => {
        return {
            ...state,
            counter: state.counter - 1,
        };
    }),

    on(reset, (state: any) => {
        return {
            ...state,
            counter: 0,
        };
    }),
    on(customIncreament, (state, counter) => {
        console.log(counter);
        return {
            ...state,
            counter: state.counter 
        }
    }),

and state:

export interface CounterState{
    
    counter: number,
    name: string
}

export const inititalState : CounterState= {
    counter: 5,
    name: 'anemoi'
}

Solution

  • its an syntax error from me,

    export const customIncreament = createAction(
        'customIncreament', props<{counter:number}>);
    

    updated code :

    export const customIncreament = createAction(
        'customIncreament', props<{counter:number}()>);
    

    need to add () to props<>()