Redux + Vanilla js

Coaspe·2021년 2월 22일
0
post-thumbnail
// Modifier(reducer)의 return 값이 application의 state의 값이 된다.
// action에 구체적인 변화가 전달된다.
// reducer는 data를 modify할 수 있는 유일한 함수이다.
// ex. countModifier가 hello를 return하므로 application의 data는 hello가 된다.
// subscribe()는 store에 변화를 감지한다.
// store는 state를 저장하는 곳이다.
// state는 application에서 변하는 값이다.
// store.dispatch(action) => redux가 reducer 함수를 호출한다.
// => countModifier(currentState = 0, {type:"HELLO"})
// dispatch는 Modifier로 message를 보낸다.
// 액션이란 type과 payload?를 갖는 object이다
// 액션 생성함수란 action object를 반환하는 함수이다.

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,
  };
};
const reducer = (state = [], action) => {
  switch (action.type) {
    case ADD_TODO:
      return [{ text: action.text, id: Date.now() }, ...state];
    case DELETE_TODO:
      return state.filter((toDo) => toDo.id !== action.id);
    default:
      return state;
  }
};

const store = createStore(reducer);

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

const dispatchdDeleteToDo = (e) => {
  const id = parseInt(e.target.parentNode.id);
  store.dispatch(deleteToDo(id));
};

const paintToDos = () => {
  const toDos = store.getState();
  ul.innerHtml = "";
  toDos.forEach((toDo) => {
    const li = document.createElement("li");
    const btn = document.createElement("button");
    btn.innerText = "DEL";
    btn.addEventListener("click", dispatchdDeleteToDo);
    li.id = toDo.id;
    li.innerText = toDo.text;
    li.appendChild(btn);
    ul.appendChild(li);
  });
};

store.subscribe(paintToDos);

const dispatchAddToDo = (text) => {
  store.dispatch(addToDo(text));
};

const onSubmit = (e) => {
  e.preventDefault();
  const toDo = input.value;
  input.value = "";
  dispatchAddToDo(toDo);
};

form.addEventListener("submit", onSubmit);
profile
https://github.com/Coaspe

0개의 댓글