Skip to content

Instantly share code, notes, and snippets.

@johnborges
Last active November 9, 2019 02:27
Show Gist options
  • Save johnborges/7cb2b8caf8c72cf861bf43ae0b6609df to your computer and use it in GitHub Desktop.
Save johnborges/7cb2b8caf8c72cf861bf43ae0b6609df to your computer and use it in GitHub Desktop.
Simple Redux Implementation without any library.
// simplified createStore function
const createStore = (reducer) => {
let listeners = [];
let currentState = reducer(undefined, {});
return {
getState: () => currentState,
dispatch: (action) => {
currentState = reducer(currentState, action);
listeners.forEach((listener) => {
listener();
});
},
subscribe: (newListener) => {
listeners.push(newListener);
const unsubscribe = () => {
listeners = listeners.filter((l) => l !== newListener);
};
return unsubscribe;
}
};
};
// Redux architecture pieces
const initialState = { count: 0 };
const actions = {
increment: { type: 'INCREMENT' },
decrement: { type: 'DECREMENT' }
};
const countReducer = (state = initialState, action) => {
switch (action.type) {
case actions.increment.type:
return {
count: state.count + 1
};
case actions.decrement.type:
return {
count: state.count - 1
};
default:
return state;
}
};
const store = createStore(countReducer);
// DOM elements. Simple Counter example. Assume these exist somewhere.
const incrementButton = document.querySelector('.increment');
const decrementButton = document.querySelector('.decrement');
// Wire click events to actions
incrementButton.addEventListener('click', () => {
store.dispatch(actions.increment);
});
decrementButton.addEventListener('click', () => {
store.dispatch(actions.decrement);
});
// Initialize UI display
const counterDisplay = document.querySelector('h1');
counterDisplay.innerHTML = parseInt(initialState.count);
// Update UI when an action fires
store.subscribe(() => {
const state = store.getState();
counterDisplay.innerHTML = parseInt(state.count);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment