2. PURE REDUX: TO DO LIST

Hapjeong Girl·2022년 11월 1일
0

MUTSA_STUDY

목록 보기
8/11
post-thumbnail

2.0 Vanilla ToDo


  1. index.html

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="utf-8" />
      <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <meta name="theme-color" content="#000000" />
      <meta name="description" content="Web site created using create-react-app" />
      <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
      <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
      <title>Vanilla Redux</title>
    </head>
    
    <body>
      <h1>To Dos</h1>
      <form>
        <input type="text" placeholder="Write to do">
        <button>dd</button>
      </form>
      <ul></ul>
    </body>
    
    </html>
  2. index.js

    const form = document.querySelector('form');
    const input = document.querySelector('input');
    const ul = document.querySelector('ul');
    
    const createToDo = (toDo) => {
    	const li = document.createElement('li');
    	li.innerText = toDo;
    	ul.appendChild(li);
    };
    
    const onSubmit = (e) => {
    	e.preventDefault();
    	const toDo = input.value;
    	input.value = '';
    	createToDo(toDo);
    };
    
    form.addEventListener('submit', onSubmit);

문제점?

  • html만 변경하는 것일뿐, application에 데이터가 저장이 안된다. → 저장하려면 내가 직접 짜야함 ⇒ 리덕스를 사용하자!

리덕스 사용

import { configureStore } 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 reducer = (state = [], action) => {
	switch (action.type) {
		case ADD_TODO:
			return [];
		case DELETE_TODO:
			return [];
		default:
			return state;
	}
};
const store = configureStore(reducer);

const onSubmit = (e) => {
	e.preventDefault();
	const toDo = input.value;
	input.value = '';
	store.dispatch({ type: ADD_TODO, text: toDo });
};

form.addEventListener('submit', onSubmit);

2.1 State Mutation


💡 State는 절대로 mutate 해서는 안 된다!
import { configureStore } 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 reducer = (state = [], action) => {
	switch (action.type) {
		case ADD_TODO:
			return [...state, { text: action.text, id: Date.now() }];
		case DELETE_TODO:
			return [];
		default:
			return state;
	}
};
const store = configureStore(reducer);

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

const onSubmit = (e) => {
	e.preventDefault();
	const toDo = input.value;
	input.value = '';
	store.dispatch({ type: ADD_TODO, text: toDo });
};

form.addEventListener('submit', onSubmit);

2.2 Delete To Do


  1. addToDo와 deleteToDo 구현하기

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


💡 filter() : 테스트를 통과한 모든 element들로 새로운 array를 만든다.
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;
	}
};

완성!

2.4 Conclusions


const reducer = (state = [], action) => {
	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;
	}
};
profile
프론트엔드 / 컴퓨터공학과 4학년

0개의 댓글