Created
September 3, 2020 13:56
-
-
Save ibare/1ed63de0c09c94a7ac79713d57b80f8d 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
import { createStore, actionCreator } from "./tiny-redux"; | |
function reducer(state = {}, { type, payload }) { | |
switch (type) { | |
case "init": | |
return { | |
...state, | |
count: payload.count | |
}; | |
case "inc": | |
return { | |
...state, | |
count: state.count + 1 | |
}; | |
case "reset": | |
return { | |
...state, | |
count: 0 | |
}; | |
default: | |
return { ...state }; | |
} | |
} | |
const store = createStore(reducer); | |
store.subscribe(() => { | |
console.log(store.getState()); | |
}); | |
store.dispatch({ | |
type: "init", | |
payload: { | |
count: 1 | |
} | |
}); | |
store.dispatch({ | |
type: "inc" | |
}); | |
store.dispatch(actionCreator("reset")); | |
const Increment = () => store.dispatch(actionCreator("inc")); | |
Increment(); | |
Increment(); | |
Increment(); |
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
export function createStore(reducer) { | |
let state; | |
const listeners = []; | |
const publish = () => { | |
listeners.forEach(({ subscriber, context }) => { | |
subscriber.call(context); | |
}); | |
}; | |
const dispatch = (action) => { | |
state = reducer(state, action); | |
publish(); | |
}; | |
const subscribe = (subscriber, context = null) => { | |
listeners.push({ | |
subscriber, | |
context | |
}); | |
}; | |
const getState = () => ({ ...state }); | |
return { | |
dispatch, | |
getState, | |
subscribe | |
}; | |
} | |
export const actionCreator = (type, payload = {}) => ({ | |
type, | |
payload: { ...payload } | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment