Skip to content

Instantly share code, notes, and snippets.

@ZhihaoLau
Created June 3, 2016 17:22
Show Gist options
  • Save ZhihaoLau/8f05969e2e6444891337638da3eefe80 to your computer and use it in GitHub Desktop.
Save ZhihaoLau/8f05969e2e6444891337638da3eefe80 to your computer and use it in GitHub Desktop.
implement createStore from scratch
const createStore = (reducer) => {
// only this place create the one and only state
let state
let listeners = []
const getState = () => state
const dispatch = (action) => {
// change state only by dispatching an action
state = reducer(state, action)
listeners.forEach(listener => listener())
}
const subscribe = (listener) => {
listeners.push(listener)
// a function for unsubscribing
return () => {
listeners = listeners.filter(l !== listener)
}
}
// initialize state
dispatch({})
return {
getState,
dispatch,
subscribe
}
}
@ZhihaoLau
Copy link
Author

check Dan's tutorial video for more imformation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment