본문 바로가기

카테고리 없음

[React] React로 할 일 관리 앱 만들기: 4장 - 할 일 수정과 데이터 저장

반응형

 

안녕하세요! 이번 포스트에서는 우리의 할 일 관리 앱에 할 일 수정 기능을 추가하고, 로컬 스토리지를 사용하여 데이터를 저장하는 방법을 알아보겠습니다.

1. 할 일 수정 기능 구현

먼저 TodoList 컴포넌트에 할 일을 수정하는 기능을 추가해 보겠습니다.

import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [editingId, setEditingId] = useState(null);

  // ... 이전 코드 ...

  const handleEdit = (id, newText) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, text: newText } : todo
      )
    );
    setEditingId(null);
  };

  return (
    <div>
      {/* ... 이전 코드 ... */}
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => handleToggle(todo.id)}
            />
            {editingId === todo.id ? (
              <input
                type="text"
                value={todo.text}
                onChange={(e) => handleEdit(todo.id, e.target.value)}
                onBlur={() => setEditingId(null)}
                autoFocus
              />
            ) : (
              <span
                style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
                onDoubleClick={() => setEditingId(todo.id)}
              >
                {todo.text}
              </span>
            )}
            <button onClick={() => handleDelete(todo.id)}>삭제</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

이 코드에서는:

  • editingId 상태를 추가하여 현재 수정 중인 할 일을 추적합니다.
  • handleEdit 함수를 추가하여 할 일의 텍스트를 수정합니다.
  • 할 일 텍스트를 더블 클릭하면 수정 모드로 전환됩니다.
  • 수정 중인 입력 필드에서 포커스가 벗어나면 수정이 완료됩니다.

2. 로컬 스토리지를 사용한 데이터 저장

이제 로컬 스토리지를 사용하여 할 일 목록을 저장하고 불러오는 기능을 구현해 보겠습니다.

import React, { useState, useEffect } from 'react';

function TodoList() {
  const [todos, setTodos] = useState(() => {
    const savedTodos = localStorage.getItem('todos');
    if (savedTodos) {
      return JSON.parse(savedTodos);
    } else {
      return [];
    }
  });
  const [inputValue, setInputValue] = useState('');
  const [editingId, setEditingId] = useState(null);

  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
  }, [todos]);

  // ... 이전 코드 ...
}

이 코드에서는:

  • useState의 초기값으로 함수를 전달하여 로컬 스토리지에서 저장된 할 일 목록을 불러옵니다.
  • useEffect 훅을 사용하여 todos 상태가 변경될 때마다 로컬 스토리지에 저장합니다.

3. 최종 TodoList 컴포넌트

모든 기능을 합친 최종 TodoList 컴포넌트는 다음과 같습니다:

import React, { useState, useEffect } from 'react';

function TodoList() {
  const [todos, setTodos] = useState(() => {
    const savedTodos = localStorage.getItem('todos');
    return savedTodos ? JSON.parse(savedTodos) : [];
  });
  const [inputValue, setInputValue] = useState('');
  const [editingId, setEditingId] = useState(null);

  useEffect(() => {
    localStorage.setItem('todos', JSON.stringify(todos));
  }, [todos]);

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (inputValue.trim() !== '') {
      setTodos([...todos, { id: Date.now(), text: inputValue, completed: false }]);
      setInputValue('');
    }
  };

  const handleDelete = (id) => {
    setTodos(todos.filter((todo) => todo.id !== id));
  };

  const handleToggle = (id) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  const handleEdit = (id, newText) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, text: newText } : todo
      )
    );
    setEditingId(null);
  };

  return (
    <div>
      <h2>할 일 목록</h2>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          placeholder="새로운 할 일을 입력하세요"
        />
        <button type="submit">추가</button>
      </form>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => handleToggle(todo.id)}
            />
            {editingId === todo.id ? (
              <input
                type="text"
                value={todo.text}
                onChange={(e) => handleEdit(todo.id, e.target.value)}
                onBlur={() => setEditingId(null)}
                autoFocus
              />
            ) : (
              <span
                style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}
                onDoubleClick={() => setEditingId(todo.id)}
              >
                {todo.text}
              </span>
            )}
            <button onClick={() => handleDelete(todo.id)}>삭제</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

실행 결과

이제 npm start 명령어로 앱을 실행하면, 할 일을 추가, 수정, 완료 표시, 삭제할 수 있으며, 페이지를 새로고침해도 데이터가 유지되는 것을 확인할 수 있습니다.

다음 단계

이번 챕터에서는 할 일 수정 기능과 로컬 스토리지를 사용한 데이터 저장 기능을 구현했습니다. 다음 챕터에서는 할 일 필터링 기능과 할 일 통계를 표시하는 기능을 추가해 보겠습니다.

React hooks(useState, useEffect)를 사용하여 상태 관리와 부수 효과를 처리하는 방법에 대해 어떻게 생각하시나요? 이 접근 방식이 코드를 더 간결하고 이해하기 쉽게 만든다고 생각하시나요? 여러분의 의견을 댓글로 남겨주세요!

반응형