How to push or update state in NgRx?

Viewed 249

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?

2 Answers

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.
  })
)

For example, in your component please inject Store constructor(private store:Store){..}

Store can be updated via this.store.dispatch(addTodo("element"))

but there is another problem. Your store should be immutable, so you cannot reuse test array in reducer.

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

is enough.

Related