Immer로 상태관리

유석현(SeokHyun Yu)·2022년 11월 21일
0

React

목록 보기
11/21
post-thumbnail

AppMentors.jsx

import React, { useState } from "react";
import { useImmer } from "use-immer";

export default function AppMentors() {
  const [person, updatePerson] = useImmer(initialPerson);
  const handleUpdate = () => {
    const name = prompt(`누구의 이름을 바꾸고 싶은가요?`);
    const current = prompt(`이름을 무엇으로 바꾸고 싶은가요?`);

    updatePerson((person) => {
      const mentor = person.mentors.find((m) => m.name === name);
      mentor.name = current;
    });
  };
  const handleAdd = () => {
    const name = prompt("name?");
    const title = prompt("title?");

    updatePerson((person) => {
      person.mentors.push({ name, title });
    });
  };
  const handleDelete = () => {
    const name = prompt("name?");

    updatePerson((person) => {
      const index = person.mentors.findIndex((m) => m.name === name);

      person.mentors.splice(index, 1);
    });
  };

  return (
    <div>
      <h1>
        {person.name}: {person.title}
      </h1>
      <p>{person.name}의 기술 스택</p>
      <ul>
        {person.mentors.map((mentor, index) => (
          <li key={index}>
            {mentor.name} ({mentor.title})
          </li>
        ))}
      </ul>
      <button onClick={handleUpdate}>스택 바꾸기</button>
      <button onClick={handleAdd}>스택 추가하기</button>
      <button onClick={handleDelete}>스택 삭제하기</button>
    </div>
  );
}

const initialPerson = {
  name: "유석현",
  title: "BackEnd Developer",
  mentors: [
    {
      name: "HTML",
      title: "title for HTML",
    },
    {
      name: "CSS",
      title: "title for CSS",
    },
  ],
};
profile
Backend Engineer

0개의 댓글