Search code examples
javascriptangulartypescriptngrxngrx-store

How to push or update state in NgRx?


I'm trying to add the inputVal value to the state. It only works on the first click, and getting this error after

Error: TypeError: Cannot add property 1, object is not extensible

import { createReducer, on } from '@ngrx/store'
import { addTodo } from '../actions/todo.actions'

export const initialState: any[] = []
let test: any[] = []

const _todoReducer = createReducer(
  initialState,
  on(addTodo, (state: any, { inputVal }) => {
    test.push(inputVal)
    state = test
    return state
  })
)

export function todoReducer(state, action) {
  return _todoReducer(state, action)
}

How do I push or update state in NgRx? or if its not possible, what's the work around for it?


Solution

  • You can never modify a state in NgRx, the reducer will return a new copy of state rather than modifying the existing one. So you can't add test to state

    try

    const _todoReducer = createReducer(
      initialState,
      on(addTodo, (state: any, { inputVal }) => {
        return [...state,inputVal] // we are creating a new array and this will become the new state.
      })
    )