2018-10-12 15:37:13 -04:00
---
title: Never Mutate State
---
2019-07-24 00:59:27 -07:00
# Never Mutate State
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Problem Explanation
2019-03-29 10:52:12 -05:00
The goal of this challenge is to return a new copy of state in reducer function because of state immutability in Redux.
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
---
## Hints
2019-03-29 10:52:12 -05:00
### Hint 1
const means: it cannot change through re-assignment, and it cannot be re-declared.
Since objects and arrays are mutable, you can add to it by index (array[3] = 3), by property (object.name="sam"), by extending (with various array methods)
2018-10-12 15:37:13 -04:00
2019-07-24 00:59:27 -07:00
### Hint 32
2019-03-29 10:52:12 -05:00
.push() and .splice() directly modify the array
2019-07-24 00:59:27 -07:00
### Hint 33
2019-03-29 10:52:12 -05:00
.concat() doesn't modify array but just returns a new array
### Hint 4
.slice() doesn't modify array but just returns a new array
### Hint 5
spread operator [...array] doesn't modify array but just returns a new array
2019-07-24 00:59:27 -07:00
---
## Solutions
< details > < summary > Solution 1 (Click to Show/Hide)< / summary >
2019-03-29 10:52:12 -05:00
```javascript
2019-07-24 00:59:27 -07:00
const ADD_TO_DO = "ADD_TO_DO";
2019-03-29 10:52:12 -05:00
// A list of strings representing tasks to do:
const todos = [
2019-07-24 00:59:27 -07:00
"Go to the store",
"Clean the house",
"Cook dinner",
"Learn to code"
2019-03-29 10:52:12 -05:00
];
const immutableReducer = (state = todos, action) => {
2019-07-24 00:59:27 -07:00
switch (action.type) {
2019-03-29 10:52:12 -05:00
case ADD_TO_DO:
// don't mutate state here or the tests will fail
2019-07-24 00:59:27 -07:00
return todos.concat(action.todo);
// or return [...todos, action.todo]
2019-03-29 10:52:12 -05:00
default:
return state;
}
};
// an example todo argument would be 'Learn React',
2019-07-24 00:59:27 -07:00
const addToDo = todo => {
2019-03-29 10:52:12 -05:00
return {
type: ADD_TO_DO,
todo
2019-07-24 00:59:27 -07:00
};
};
2019-03-29 10:52:12 -05:00
const store = Redux.createStore(immutableReducer);
```
2019-07-24 00:59:27 -07:00
< / details >