Skip to content

Instantly share code, notes, and snippets.

@auxcoder
Last active January 30, 2020 15:11
Show Gist options
  • Save auxcoder/e3eaab064dbbfb775f2eca499623cb81 to your computer and use it in GitHub Desktop.
Save auxcoder/e3eaab064dbbfb775f2eca499623cb81 to your computer and use it in GitHub Desktop.
A simple recreation of Redux
// from: https://repl.it/@dericgw/ReduxRecreated
// There area lot more checks in the Redux lib but this gets the point across.
function createStore(reducer, initialState) {
let currentState = initialState;
const listeners = [];
const getState = () => currentState;
function subscribe(listener) {
listeners.push(listener);
return function unsubscribe() {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
}
}
function dispatch(action) {
currentState = reducer(currentState, action);
listeners.forEach(listener => listener());
return action;
}
dispatch({ type: 'INIT'});
return {
getState,
subscribe,
dispatch,
};
}
// End the Redux implementation
// Reducer
function reducer(state = { firstName: 'John', lastName: 'Smith' }, action) {
switch (action.type) {
case 'UPDATE_FIRSTNAME':
return {
...state,
firstName: action.payload,
};
case 'UPDATE_LASTNAME':
return {
...state,
lastName: action.payload,
};
default:
return state;
}
}
// Action creators
const updateFirstName = firstName => ({
type: 'UPDATE_FIRSTNAME',
payload: firstName,
});
const updateLastName = lastName => ({
type: 'UPDATE_LASTNAME',
payload: lastName,
});
// Create the store
const store = createStore(reducer);
// Get initial state
console.log(`INITIAL STATE: ${JSON.stringify(store.getState())}`);
// Subscribe to state changes
const unsub = store.subscribe(() => {
console.log(`Subscription fired`, JSON.stringify(store.getState()));
})
// Dispatch an action
store.dispatch(updateFirstName('Tommy'));
// Unsubscribe our listener
unsub();
// Dispatch another action
store.dispatch(updateLastName('Watson'));
// Get the current state
console.log(JSON.stringify(store.getState()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment