Skip to content

Instantly share code, notes, and snippets.

@WendySanarwanto
Last active May 4, 2018 20:45
Show Gist options
  • Save WendySanarwanto/8b7a3cf0eb940a6ea7a8c719341e82f8 to your computer and use it in GitHub Desktop.
Save WendySanarwanto/8b7a3cf0eb940a6ea7a8c719341e82f8 to your computer and use it in GitHub Desktop.
Understanding Redux
import Redux from 'redux';
// declare a function which takes state & action args (the reducer)
const reducer = (state = [], action) => {
// Act based on specific action.type
if (action.type === 'split_string') {
return action.payload.split(' ');
}
else if (action.type === 'add_char') {
return [...state, '!'];
}
// Otherwise, just return the state arg.
return state;
};
// Create a store
const { createStore } = Redux;
const store = createStore( reducer );
// Get current state from created store
store.getState(); // return []
// Declare an action whose type is 'split_string' and data is 'hello redux'
const action = {
type: 'split_string',
payload: 'hello redux'
};
store.dispatch(action); // request the reducer to work against this action
store.getState(); // it should return ['hello', 'redux'] now
// create 2nd action
const action2 = {
type: 'add_char',
payload: '!'
};
// Dispatch the 2nd action
store.dispatch(action2);
// Get the state
store.getState(); // it should return ['hello', 'redux', '!']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment