Skip to content

Instantly share code, notes, and snippets.

@primedime
Last active December 27, 2017 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save primedime/e2334399bf71141dba246125a9601a5e to your computer and use it in GitHub Desktop.
Save primedime/e2334399bf71141dba246125a9601a5e to your computer and use it in GitHub Desktop.
Quick example of how to properly use Redux
/* 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