January 12, 2021
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)
๋ค ๋ชจ๋ฅด๊ฒ ๊ณ ์ด๊ฒ๋ง ๋ซ์ด์ ธ๋ผ ๋ณด๋ค๊ฐ ์๋ จ๋ค.