-
Notifications
You must be signed in to change notification settings - Fork 0
[동현] State-Management #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: donghyun
Are you sure you want to change the base?
Changes from all commits
ddabff3
c72b4b0
8248cd0
c8a5ee9
44b3865
119f8b9
c8beed5
ffb73a0
cfd17fc
07e8e45
ac28340
f2996ce
1bba98d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import isPlainObject from '../utils/isPlainObject' | ||
| import type { Reducer, ActionType, ListenerCallback } from './redux.type' | ||
| import { ActionTypes } from './redux.utils' | ||
|
|
||
| export function createStore<State, Action extends ActionType>(reducer: Reducer<State, Action>) { | ||
| let currentState: State | ||
| let currentListenerId = 0 | ||
| let currentListeners: Map<number, ListenerCallback> = new Map() | ||
|
|
||
| const getState = () => currentState | ||
|
|
||
| const dispatch = (action: Action) => { | ||
| if (!isPlainObject(action)) { | ||
| throw new Error(`해당 ${action}은 순수 객체가 아니에요! action은 항상 순수 객체여야 합니다.`) | ||
| } | ||
|
|
||
| if (typeof action.type !== 'string') { | ||
| throw new Error(`action type은 반드시 문자열이어야 합니다.`) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 타입스크립트는 컴파일 시 타입 에러를 발생시키고, 런타임에서의 타입 안전성을 보장하지 않기 때문에 예외 처리 등을 해야 한다는 걸 덕분에 배웠습니다!! |
||
| } | ||
|
|
||
| currentState = reducer(currentState, action) | ||
| currentListeners.forEach((listener) => listener()) | ||
|
|
||
| return action as Action | ||
| } | ||
|
|
||
| const subscribe = (listenerCallback: ListenerCallback) => { | ||
| if (typeof listenerCallback !== 'function') { | ||
| throw new Error(`subscribe 매개변수는 반드시 함수이어야 합니다.`) | ||
| } | ||
|
|
||
| const listenerId = currentListenerId++ | ||
| currentListeners.set(listenerId, listenerCallback) | ||
| currentListeners.forEach((listener) => listener()) | ||
|
|
||
| return () => { | ||
| currentListeners.delete(listenerId) | ||
| } | ||
| } | ||
|
|
||
| dispatch({ type: ActionTypes.INIT } as Action) | ||
|
|
||
| return { | ||
| getState, | ||
| dispatch, | ||
| subscribe, | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| export type Reducer<State, Action> = (state: State, action: Action) => State | ||
|
|
||
| export type ListenerCallback = () => void | ||
|
|
||
| export interface ActionType<T extends string = string> { | ||
| type: T | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| const randomString = () => Math.random().toString(36).substring(7).split('').join('.') | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이건 어떤 용도인가요? |
||
|
|
||
| export const ActionTypes = { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. action의 초기 값을 지정하는 건가요?? |
||
| INIT: `@@redux/INIT${randomString()}`, | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,39 @@ | ||
| // your code | ||
| import { createStore } from './core/redux' | ||
| import { additionReducer, ACTION_TYPE } from './reducer' | ||
|
|
||
| const { getState, dispatch, subscribe } = createStore(additionReducer) | ||
|
|
||
| const rootElement = document.getElementById('app')! as HTMLDivElement | ||
|
|
||
| // Todo: 상태가 객체일 때 | ||
| // const render = () => { | ||
| // rootElement.innerHTML = ` | ||
| // <p>a + b = ${getState().a + getState().b}</p> | ||
| // <input id="stateA" value="${getState().a}" /> | ||
| // <input id="stateB" value="${getState().b}" /> | ||
| // ` | ||
|
|
||
| // rootElement.querySelector('#stateA')!.addEventListener('change', (event) => { | ||
| // const target = event.target as HTMLInputElement | ||
| // dispatch({ type: ACTION_TYPE.SET_A, payload: { a: Number(target.value) } }) | ||
| // }) | ||
|
|
||
| // rootElement.querySelector('#stateB')!.addEventListener('change', (event) => { | ||
| // const target = event.target as HTMLInputElement | ||
| // dispatch({ type: ACTION_TYPE.SET_B, payload: { b: Number(target.value) } }) | ||
| // }) | ||
| // } | ||
|
|
||
| // Todo: 상태가 number 일 때 | ||
| const render = () => { | ||
| rootElement.innerHTML = ` | ||
| <p>${getState()}</p> | ||
| <button id="increase">+1</button> | ||
| <button id="decrease">-1</button> | ||
| ` | ||
|
|
||
| rootElement.querySelector('#increase')!.addEventListener('click', () => dispatch({ type: ACTION_TYPE.INCREASE })) | ||
| rootElement.querySelector('#decrease')!.addEventListener('click', () => dispatch({ type: ACTION_TYPE.DECREASE })) | ||
| } | ||
|
|
||
| subscribe(render) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| /** | ||
| * Object 사용 예시 | ||
| */ | ||
|
|
||
| // interface InitialState { | ||
| // a: number | ||
| // b: number | ||
| // } | ||
|
|
||
| // const initialState = { | ||
| // a: 10, | ||
| // b: 20, | ||
| // } | ||
|
|
||
| // export const ACTION_TYPE = { | ||
| // SET_A: 'redux/SET_A', | ||
| // SET_B: 'redux/SET_B', | ||
| // } as const | ||
|
|
||
| // type Action = | ||
| // | { type: typeof ACTION_TYPE.SET_A; payload: Pick<InitialState, 'a'> } | ||
| // | { type: typeof ACTION_TYPE.SET_B; payload: Pick<InitialState, 'b'> } | ||
|
|
||
| // export const additionReducer = (state: InitialState = initialState, action: Action): InitialState => { | ||
| // switch (action.type) { | ||
| // case ACTION_TYPE.SET_A: | ||
| // return { ...state, a: action.payload.a } | ||
|
|
||
| // case ACTION_TYPE.SET_B: | ||
| // return { ...state, b: action.payload.b } | ||
|
|
||
| // default: | ||
| // return state | ||
| // } | ||
| // } | ||
|
|
||
| /** | ||
| * Number 사용 예시 | ||
| */ | ||
| const initialState = 0 | ||
|
|
||
| export const ACTION_TYPE = { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. type이나 util은 파일을 분리했는데 왜 상수는 파일을 분리하지 않으신건가요??
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. type, util 파일을 분리한 곳은 아마 redux를 만든 곳일거에요. 거기는 코드가 조금 많아서 분리하는게 좋다라는 생각이였고, 사용하는 reducer에서는 한 파일에 모두 다 넣었습니다! 사용하는 입장에서 규모가 크지않다면 한 파일로 작성하는게 좋겠다 라는 생각을 했어요! |
||
| INCREASE: 'increase', | ||
| DECREASE: 'decrease', | ||
| } as const | ||
|
|
||
| type Action = { type: typeof ACTION_TYPE.INCREASE } | { type: typeof ACTION_TYPE.DECREASE } | ||
|
|
||
| export const additionReducer = (state: number = initialState, action: Action): number => { | ||
| switch (action.type) { | ||
| case ACTION_TYPE.INCREASE: | ||
| return state + 1 | ||
|
|
||
| case ACTION_TYPE.DECREASE: | ||
| return state <= 0 ? 0 : state - 1 | ||
|
|
||
| default: | ||
| return state | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| export default function isPlainObject(obj: any): obj is object { | ||
| if (typeof obj !== 'object' || obj === null) return false | ||
|
|
||
| let proto = obj | ||
| while (Object.getPrototypeOf(proto) !== null) { | ||
| proto = Object.getPrototypeOf(proto) | ||
| } | ||
|
|
||
| return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
에러 처리 굿입니다!