* fix: restructure certifications guide articles * fix: added 3 dashes line before prob expl * fix: added 3 dashes line before hints * fix: added 3 dashes line before solutions
53 lines
1.0 KiB
Markdown
53 lines
1.0 KiB
Markdown
---
|
|
title: Copy an Object with Object.assign
|
|
---
|
|
# Copy an Object with Object.assign
|
|
|
|
---
|
|
## Problem Explanation
|
|
The goal of this challenge is to enforce state immutability when state is an object.
|
|
|
|
|
|
---
|
|
## Hints
|
|
|
|
### Hint 1
|
|
Use the method ```Object.assign({}, obj1, obj2)``` in return. Pass ```state``` as obj1.
|
|
|
|
### Hint 2
|
|
The obj2 should be the updated ```{key: value}``` pair of your state.
|
|
|
|
|
|
---
|
|
## Solutions
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
```javascript
|
|
const defaultState = {
|
|
user: "CamperBot",
|
|
status: "offline",
|
|
friends: "732,982",
|
|
community: "freeCodeCamp"
|
|
};
|
|
|
|
const immutableReducer = (state = defaultState, action) => {
|
|
switch (action.type) {
|
|
case "ONLINE":
|
|
// to enforce state immutability, return a new state object using Object.assign() method
|
|
return Object.assign({}, state, { status: "online" });
|
|
default:
|
|
return state;
|
|
}
|
|
};
|
|
|
|
const wakeUp = () => {
|
|
return {
|
|
type: "ONLINE"
|
|
};
|
|
};
|
|
|
|
const store = Redux.createStore(immutableReducer);
|
|
```
|
|
</details>
|