Skip to content

Instantly share code, notes, and snippets.

@estevanmaito
Created March 8, 2019 14:54
Show Gist options
  • Save estevanmaito/138c2d0e9d15fa6f2dbcaac2ab6e66cd to your computer and use it in GitHub Desktop.
Save estevanmaito/138c2d0e9d15fa6f2dbcaac2ab6e66cd to your computer and use it in GitHub Desktop.
Redux study implementation
// 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);
const index = listeners.indexOf(listener);
return function unsubscribe() {
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