Last active
December 27, 2017 17:50
-
-
Save primedime/e2334399bf71141dba246125a9601a5e to your computer and use it in GitHub Desktop.
Quick example of how to properly use Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Create Reducer, which is a function | |
that produces some amount of state | |
*/ | |
const reducer = (state = [], action) => { | |
if (action.type === 'split_string') { | |
return action.payload.split(''); | |
} else if (action.type === 'add_character') { | |
// Make a new array | |
// Take all elements in current State array | |
// Add action.payload to new State | |
return [ ...state, action.payload ]; | |
}; | |
return state; | |
}; | |
// Create a Store & pass it the Reducer | |
const store = Redux.createStore(reducer); | |
// This is our empty state | |
store.getState(); | |
/* Create an Action, which is a vary | |
specific directive to tell the | |
Reducer how to update its State | |
*/ | |
const action = { | |
type: 'split_string', // The command | |
payload: 'asdf' // Data we want to communicate to the Reducer | |
}; | |
// Send the Action to the Reducer | |
store.dispatch(action); | |
// Get current State | |
store.getState(); | |
// Add another Action to perform | |
const action2 = { | |
type: 'add_character', | |
payload: 'a' | |
}; | |
// Send the Action to the Reducer | |
store.dispatch(action2); | |
// Get current State | |
store.getState(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment