0

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
    })
  })
Niragh
  • 162
  • 2
  • 10

2 Answers2

1

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()

Naresh
  • 941
  • 9
  • 22
0

JavaScript Object.assign() is a constructor method used to construct a new target object from an existing source object. The method creates a copy of the source object and delivers the target object, only if you provide an empty object as the first argument. You can use a source object directly and the modified values are overwritten to the new copy of source object.

In the documentation site, it clearly mentions this.

enter image description here

Dharman
  • 30,962
  • 25
  • 85
  • 135
wr93_
  • 130
  • 1
  • 1
  • 13