Skip to content

Instantly share code, notes, and snippets.

@tanvirraj
Created March 11, 2019 17:14
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 tanvirraj/c214ff6df686ecb5a0c9f6a13cd11ffe to your computer and use it in GitHub Desktop.
Save tanvirraj/c214ff6df686ecb5a0c9f6a13cd11ffe to your computer and use it in GitHub Desktop.
// There area lot more checks in the Redux lib but this gets the point across.
function createStore(reducer, initialState) {
let currentState = initialState;
const listeners = [];
function getState() {
return currentState;
}
function subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('A listener must be a function');
}
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