Search code examples
reactjsreduxredux-reducers

In redux reducers when updating, should it not be state.slice().map instead of state.map()?


So I was going through the redux documentation on Reducers topic, and they had mentioned it should be pure functions. I understand this is for comparing whether the state object is the same or old. But I noticed the following code snippet at Redux Reducers documentation

case TOGGLE_TODO:
  return Object.assign({}, state, {
    todos: state.todos.map((todo, index) => {
      if (index === action.index) {
        return Object.assign({}, todo, {
          completed: !todo.completed
        })
      }
      return todo
    })
  })

Here they are directly accessing the state.todos array and using map operator. This means that map will update the state parameter passed. Considering reducer being pure function here, we should not update parameters itself here right?

Why are we/they not using slice() here like it should be below?

case TOGGLE_TODO:
  return Object.assign({}, state, {
    todos: state.todos.slice().map((todo, index) => {
      if (index === action.index) {
        return Object.assign({}, todo, {
          completed: !todo.completed
        })
      }
      return todo
    })
  })

Solution

  • According to the Docs "The map() method creates a new array populated with the results of calling a provided function on every element in the calling array." so We are not muatating the state params passed to the reducer function hence its a pure function.

    map() already returns a new array so there's to no need to use slice()