Commented solution using switch statement (#35623)
* Commented solution using switch statement * fix: used two-space indentation
This commit is contained in:
committed by
Randell Dawson
parent
2565d4c44a
commit
25c906d389
@ -3,35 +3,34 @@ title: Extract State Logic to Redux
|
|||||||
---
|
---
|
||||||
## Extract State Logic to Redux
|
## Extract State Logic to Redux
|
||||||
|
|
||||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/react-and-redux/extract-state-logic-to-redux/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
|
||||||
|
|
||||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
|
||||||
|
|
||||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
|
||||||
|
|
||||||
Suggested solution:
|
|
||||||
|
|
||||||
|
### Solution
|
||||||
```javascript
|
```javascript
|
||||||
|
// define ADD, addMessage(), messageReducer(), and store here:
|
||||||
const ADD = 'ADD';
|
const ADD = 'ADD';
|
||||||
|
const addMessage = (message) => {
|
||||||
function addMessage(message) {
|
return ({
|
||||||
return {
|
|
||||||
type: ADD,
|
type: ADD,
|
||||||
message: message
|
message
|
||||||
};
|
})
|
||||||
};
|
|
||||||
|
|
||||||
function messageReducer (previousState, action) {
|
|
||||||
return [...previousState, action.message];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let store = {
|
// Use ES6 default paramter to give the 'previousState' parameter an initial value.
|
||||||
state: [],
|
const messageReducer = (previousState = [], action) => {
|
||||||
getState: () => store.state,
|
|
||||||
dispatch: (action) => {
|
// Use switch statement to lay out the reducer logic in response to different action type
|
||||||
if (action.type === ADD) {
|
switch (action.type) {
|
||||||
store.state = messageReducer(store.state, action);
|
case ADD:
|
||||||
}
|
|
||||||
|
// Use ES6 spread operator to return a new array where the new message is added to previousState
|
||||||
|
return [...previousState, action.message]
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
// A default case to fall back on in case if the update to Redux store is not for this specific state.
|
||||||
|
return previousState;
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
|
const store = Redux.createStore(messageReducer);
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user