Commented solution using switch statement (#35623)

* Commented solution using switch statement

* fix: used two-space indentation
This commit is contained in:
Ina S.Lew
2019-03-29 16:33:47 +01:00
committed by Randell Dawson
parent 2565d4c44a
commit 25c906d389

View File

@ -3,35 +3,34 @@ title: 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
// define ADD, addMessage(), messageReducer(), and store here:
const ADD = 'ADD';
function addMessage(message) {
return {
const addMessage = (message) => {
return ({
type: ADD,
message: message
};
};
function messageReducer (previousState, action) {
return [...previousState, action.message];
message
})
}
let store = {
state: [],
getState: () => store.state,
dispatch: (action) => {
if (action.type === ADD) {
store.state = messageReducer(store.state, action);
}
// Use ES6 default paramter to give the 'previousState' parameter an initial value.
const messageReducer = (previousState = [], action) => {
// Use switch statement to lay out the reducer logic in response to different action type
switch (action.type) {
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);
```