Skip to content

Instantly share code, notes, and snippets.

@CHR15-
Last active January 11, 2020 00:17
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 CHR15-/74ac0e9a2168f212113e0c12f35299ed to your computer and use it in GitHub Desktop.
Save CHR15-/74ac0e9a2168f212113e0c12f35299ed to your computer and use it in GitHub Desktop.
Redux Theory
const reduxFlow = {
1: "A call is made somewhere which dispatches an action",
2: "This action is passed into a reducer",
3: "That reducer then returns some new state",
4: "That state is updated in the store/state tree",
5: "Subscribers are then notified about the new state."
}
// Example store creation
const createStore = (reducer, initState = {}, enhancer) => {
/*
Enhancer === middleware. This Returns a new version of our store which allows
for us to do things before and after a dispatch is called.
*/
if (enhancer) return enhancer(createStore)(initReducer, initState);
let currentReducer = reducer;
let currentState = initState;
let currentSubs = [];
//
let state = reducer(initState, { 'type': '__INIT__' });
return {
// Returns a single state tree of.. well... state!
getState() {
return state;
},
/*
An action occurred, call our reducer with our state and proposed changes.
Also, let subscribers know about our updated state tree.
*/
dispatch(action) {
state = reducer(state, action);
subs.forEach(sub => sub());
},
/*
Subscribers that listen to change on the state tree.
Also, gift newly subbed functions the ability to unsub
*/
subscribe(listener) {
subs.push(listener);
return () => {
subs = subs.filter(sub => sub !== listener);
}
},
/*
Swap out our reducer with a new one, then dispatch an action
to re-create the state with the new reducer!
*/
replaceReducer(newReducer) {
reducer = newReducer;
this.dispatch({'type': '__REPLACE__'});
}
};
}
// Example of creating a store and fetching the state
const store = createStore();
const state = store.getState();
// Subscribe to a store, watch for change!
store.subscribe(() => console.log('The state changed!', store.getState()));
/*
Reduces are functions that takes the current state and an action as input,
returning the next state iteration (after an action has happened).
*/
const countReducer = (state = 0, action) => {
switch(action.type) {
case 'INC':
state += 1
break;
case 'DEC':
state -= 1
break;
}
return state;
}
const countInvocation = countReducer(5, 'INC');
store.dispatch({
'type': 'DO_THINGS',
'text': 'things'
});
/*
How does this connect with React?
You'll be passing the above store into React's Provider component which
grants access to the rest of the application encapusated within said Provider
via a connect() function.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment