개발자를 향해...

[초보자를 위한 리덕스 101] #2.2 Delete To Do ~ #2.4 Conclusions 본문

웹 자바스크립트 공부/ReactJS + node.js

[초보자를 위한 리덕스 101] #2.2 Delete To Do ~ #2.4 Conclusions

eugeneHwang1124 2021. 3. 9. 19:48
728x90
반응형

본 글은 노마드코더 님의 [초보자를 위한 리덕스 101]을 수강하며 작성하였습니다.

 

#2.2 Delete To Do

배열에서 삭제하는 기능을 만들어보자.

우선 입력한 리스트를 ul에 넣고 삭제 버튼을 같이 나열한다. 삭제할 때에는 id를 통해 삭제한다.

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) => {
  console.log(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 dispatchAddToDo = text => {
  store.dispatch(addToDo(text));
};

const dispatchDeleteToDo = e => {
  const id = 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", 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);

 

 

#2.3 Delete To Do part Two

splice를 통해 배열의 내용을 mutat할 수 있지만 이것은 우리가 원하는 것이 아니다. 대신 우리는 filter를 살펴보자. 이 필터는 우리는 배열을 새롭게 생성할 수 있다.  특히 조건을 만족하는 배열들의 요소로 배열을 새롭게 생성한다.이를 이용해 deleteTodos에서 사용해보자. 삭제할 아이디를 가지고 있징 않은 아이디들을 모두 새로운 배열에 할당한다.

case DELETE_TODO:
       return state.filter(toDo => toDo.id !== action.id);

 

#2.4 Conclusions

 

const addToDo = text => {
  return {
    type: ADD_TODO,
    text
  };
};

이 구조는 우리가action에  보내는 입력 양식이다. object를 리턴한다.우리는 새로운 요소를 추가하기 위해 새로운 배열을 생성해 리턴한다.

이 코드는 다음과 같이 바꿀 수도 있다.

case ADD_TODO:
      const newToDoObj = { text: action.text, id: Date.now() };
      return [newToDoObj, ...state];

마찬가지로 DELETE_TODE 도 다음과 같이 바꿀 수 있다.

switch(action.type){
    case ADD_TODO:
      const newToDoObj = { text: action.text, id: Date.now() };
      return [newToDoObj, ...state];
    case DELETE_TODO:
      const cleaned = state.filter(toDo => toDo.id !== action.id);
      return cleaned;
    default:
      return state;

이제 우리는 todo의 변화에 맞게 리스트를 리페인트하고 있다.

반응형