Last active
July 4, 2023 15:36
-
-
Save ibare/0eb8597551070bf1ebf8e797439913a3 to your computer and use it in GitHub Desktop.
Tiny Redux
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 "./redux-middleware"; | |
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 logger = (store) => (next) => (action) => { | |
console.log("logger: ", action.type); | |
next(action); | |
}; | |
const monitor = (store) => (next) => (action) => { | |
setTimeout(() => { | |
console.log("monitor: ", action.type); | |
next(action); | |
}, 2000); | |
}; | |
const store = createStore(reducer, [logger, monitor]); | |
store.subscribe(() => { | |
console.log(store.getState()); | |
}); | |
store.dispatch({ | |
type: "init", | |
payload: { | |
count: 1 | |
} | |
}); | |
store.dispatch({ | |
type: "inc" | |
}); | |
const Reset = () => store.dispatch(actionCreator("reset")); | |
const Increment = () => store.dispatch(actionCreator("inc")); | |
Increment(); | |
Reset(); | |
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, middlewares = []) { | |
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 }); | |
const store = { | |
dispatch, | |
getState, | |
subscribe | |
}; | |
middlewares = Array.from(middlewares).reverse(); | |
let lastDispatch = store.dispatch; | |
middlewares.forEach((middleware) => { | |
lastDispatch = middleware(store)(lastDispatch); | |
}); | |
return { ...store, dispatch: lastDispatch }; | |
} | |
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
디버깅 setting 은 어떻게 만드나요??