Skip to content

Instantly share code, notes, and snippets.

@reime005
Created December 27, 2020 22:48
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 reime005/ac59255663e93012dc0f51dc1375ac7c to your computer and use it in GitHub Desktop.
Save reime005/ac59255663e93012dc0f51dc1375ac7c to your computer and use it in GitHub Desktop.
const actionTypes = {
ACTION_TYPE_TEST: 'ACTION_TYPE_TEST'
}
class Store {
constructor(initialState = { testValue: 0 }) {
this.state = initialState;
this.subscribers = [];
}
dispatch(action) {
this.state = reducer(this.state, action);
this.notifySubscribers();
return action;
}
notifySubscribers() {
this.subscribers.forEach(subscriber => {
subscriber(this.state);
});
}
subscribe(fn) {
this.subscribers.push(fn);
}
getState() {
return this.state;
}
}
const reducer = (state, { type, payload }) => {
switch (type) {
case actionTypes.ACTION_TYPE_TEST: {
return {
...state,
testValue: payload
}
}
default: {
return state;
}
}
}
const myStore = new Store(); // 0
myStore.subscribe(newState => console.warn(newState));
console.warn(myStore.getState().testValue);
myStore.dispatch({ type: actionTypes.ACTION_TYPE_TEST, payload: 42 });
console.warn(myStore.getState().testValue); // 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment