๐ŸคRedux - Part 1. Vanilla JS + Redux

๐Ÿค์ž ์ž๊ธฐ ์ „ ์ด๋ถˆ ์†์—์„œ ๋ณผ ์šฉ๋„ - 1

redux1

import { createStore } from 'redux'

const form = document.querySelector('form')
const input = document.querySelector('input')
const ul = document.querySelector('ul')

const ADD_TODO = 'ADD_TODO'
const DELETE_TODO = 'DELETE_TODO'

// ! action creator addToDo, it only returns object
const addToDo = text => {
  return {
    type: ADD_TODO,
    text,
  }
}

// ! action creator deleteToDo, it only returns object
const deleteToDo = id => {
  return {
    type: DELETE_TODO,
    id,
  }
}

const reducer = (state = [], action) => {
  console.log(state, action)
  switch (action.type) {
    case ADD_TODO:
      return [...state, { text: action.text, id: Date.now() }]
    case DELETE_TODO:
      return state.filter(todo => todo.id !== action.id)
    default:
      return state
  }
}

const store = createStore(reducer) // ! ์ƒํƒœ๋ฅผ ์ €์žฅํ•˜๋Š” store ๊ฐœ์„ค, ํ•˜์ง€๋งŒ reducer ๊ฐ€ ํ•„์š”ํ•˜์ง€

store.subscribe(() => console.log(store.getState()))

// submit button ์„ ๋ˆ„๋ฅด๋ฉด ์‹คํ–‰๋˜๋Š” dispatchAddTodo
const dispatchAddTodo = text => {
  store.dispatch(addToDo(text)) // reducer ์— action ์„ ์ „๋‹ฌ!
}

// Del ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด ์‹คํ–‰๋˜๋Š” dispatchDeleteToDo
const dispatchDeleteToDo = e => {
  // ! html ์—์„œ์˜ id ๋Š” ๋ฌธ์ž์—ด ํƒ€์ž…์ด๊ธฐ์— ์ •์ˆ˜๋กœ ๋ณ€ํ™˜
  const id = parseInt(e.target.parentNode.id)
  store.dispatch(deleteToDo(id))
}

const paintToDos = () => {
  const toDos = store.getState()
  // ! paintToDos ๋ฅผ ํ˜ธ์ถœ ํ•  ๋•Œ๋งˆ๋‹ค ul ์ด ์‹น ์ง€์›Œ์กŒ๋‹ค๊ฐ€ ์•„๋ž˜๋ฅผ ์‹คํ–‰ํ•˜๊ฒŒ ํ•œ๋‹ค.
  ul.innerHTML = ''
  toDos.forEach(toDo => {
    const li = document.createElement('li')
    const btn = document.createElement('button')
    btn.innerText = 'DEL'

    btn.addEventListener('click', dispatchDeleteToDo) // ! ์—ฌ๊ธฐ ์ฃผ๋ชฉ

    li.id = toDo.id
    li.innerText = toDo.text
    li.appendChild(btn)
    ul.appendChild(li)
  })
}

// ! ๊ตฌ๋…, ์Šคํ† ์–ด์˜ ์ƒํƒœ๊ฐ€ ๋ฐ”๋€” ๋•Œ๋งˆ๋‹ค ์•Œ๋ ค์ฃผ๋Š” (์‹ค์ œ ํ™”๋ฉด์— ๋ฐ˜์˜๋˜๊ฒŒ ํ•˜๋Š”) ์—ญํ• ์„ ํ•œ๋‹ค.
store.subscribe(paintToDos)

const onSubmit = e => {
  e.preventDefault()
  const toDo = input.value
  input.value = ''
  dispatchAddTodo(toDo)
}

form.addEventListener('submit', onSubmit)

๋‹ค ๋ชจ๋ฅด๊ฒ ๊ณ  ์ด๊ฒƒ๋งŒ ๋šซ์–ด์ ธ๋ผ ๋ณด๋‹ค๊ฐ€ ์ž๋ จ๋‹ค.


Written by@[DotoriMook]
ํ”„๋ก ํŠธ์—”๋“œ ์ฃผ๋‹ˆ์–ด ๊ฐœ๋ฐœ์ž ๋„ํ† ๋ฆฌ๋ฌต์˜ ๊ธฐ์ˆ ๊ฐœ๋ฐœ ๋ธ”๋กœ๊ทธ ์ž…๋‹ˆ๋‹ค.

GitHubMediumTwitterFacebook