Skip to content
4 changes: 2 additions & 2 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"singleQuote": true,
"semi": true,
"semi": false,
"useTabs": false,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 80,
"printWidth": 120,
"bracketSpacing": true,
"arrowParens": "always",
"endOfLine": "auto"
Expand Down
6 changes: 3 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<!doctype html>
<html lang="en">
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
<title>상태관리 만들기</title>
</head>
<body>
<div id="app"></div>
Expand Down
48 changes: 48 additions & 0 deletions src/core/redux.ts
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은 항상 순수 객체여야 합니다.`)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

에러 처리 굿입니다!

}

if (typeof action.type !== 'string') {
throw new Error(`action type은 반드시 문자열이어야 합니다.`)
Copy link

Choose a reason for hiding this comment

The 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,
}
}
7 changes: 7 additions & 0 deletions src/core/redux.type.ts
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
}
5 changes: 5 additions & 0 deletions src/core/redux.utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const randomString = () => Math.random().toString(36).substring(7).split('').join('.')
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이건 어떤 용도인가요?


export const ActionTypes = {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

action의 초기 값을 지정하는 건가요??

INIT: `@@redux/INIT${randomString()}`,
}
40 changes: 39 additions & 1 deletion src/main.ts
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)
60 changes: 60 additions & 0 deletions src/reducer.ts
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 = {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

type이나 util은 파일을 분리했는데 왜 상수는 파일을 분리하지 않으신건가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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
}
}
10 changes: 10 additions & 0 deletions src/utils/isPlainObject.ts
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
}