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"
const addToDo = (text) => {
return {
type: ADD_TODO,
text
}
}
const deleteToDo = (id) => {
return {
type: DELETE_TODO,
id
}
}
// NOT RECOMENDED MUTATION STATE // --- !!
// const reducer = (state = [], { type, text }) => {
// switch (type) {
// case ADD_TODO:
// state.push(text)
// return state
// case DELETE_TODO:
// return []
// default:
// return state
// }
// }
const reducer = (state = [], { type, text, id }) => {
switch (type) {
case ADD_TODO:
return [{ text, id: Date.now() }, ...state ]
case DELETE_TODO:
return state.filter(todo => {
return todo.id !== +id
})
default:
return state
}
} // === @@
const store = createStore(reducer) // --- (1)
const paintoDos = () => {
ul.innerHTML = ''
const toDos = store.getState()
toDos.forEach(toDo => {
const li = document.createElement('li')
li.innerHTML = toDo.text
li.id = toDo.id
const button = document.createElement('button')
button.innerHTML = 'DELETE'
button.addEventListener("click", dispatchDeleteToDo)
li.appendChild(button)
ul.appendChild(li)
})
}
store.subscribe(paintoDos) // --- (2)
const dispatchAddToDo = text => {
store.dispatch(addToDo(text))
} // --- (3)
const dispatchDeleteToDo = e => {
const { id }= e.target.parentNode
store.dispatch(deleteToDo(id))
}
const getInputValue = () => {
const value = input.value
input.value = ''
return value
}
const onSubmit = e => {
e.preventDefault()
const toDo = getInputValue()
dispatchAddToDo(toDo)
}
form.addEventListener("submit", onSubmit) // --- (4)
state
를 관리할 modifier
와 함께 store
를 생성한다. state가
변경되었을 때, HTML도 변경될 수 있도록 한다.modifier
를 실행시킨다. addToDo
는 modifier
에서 요구하는 파라미터의 인터페이스(명세서)인 느낌이다. 휴먼에러 예방과 빠른 코드파악을 위해 이처럼 작성하기도 한다고 한다. 따라서 addToDo
와 dispatchAddToDo
를 분리하였다.eventListener
를 사용하여 submit할 경우, input
값의 value
를 할 일 목록에 추가하는 함수 onSumit
를 실행시킨다.(!!)와 (@@)의 차이점