Created
March 11, 2019 17:14
-
-
Save tanvirraj/c214ff6df686ecb5a0c9f6a13cd11ffe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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