[오류리뷰] zustand 형식

Yunseok Choi·2024년 3월 27일

EARTH-IDE-N 프로젝트

목록 보기
6/9

1️⃣ 에러 상황

interface aboutEditor {
  content: string;
  showContent: (id: string, contents: string) => void;
}

const editorStore = create<aboutEditor>((set) => ({
  content: "",
  showContent: (id, contents) => set(state=> { state.content: contents }),
}));

처음 코드를 이렇게 썼는데 타입 에러가 났다. 둘 다 string 타입으로 주고, 넘어오는 값들도 다 string인데 도대체 무슨 에러인지 Partial<>에러가 났다는데, 어디서 굴러 들어온 놈인지.. 여러가지를 고쳐보고 시도를 해봤지만 결국 포기하고 chatGPT한테 물어봤다. 흠.. 답을 잘 알려줬다..

2️⃣ 고쳐진 코드

interface aboutEditor {
  content: string;
  showContent: (id: string, contents: string) => void;
}

const editorStore = create<aboutEditor>((set) => ({
  content: "",
  showContent: (_, contents) => set({ content: contents }),
}));

에러가 난 이유는 타입때문이 아니라, 할당관련 문제였다. showContent()라는 함수가 하려는 행위는 content의 상태를 변경하려는 것인데, 처음 코드는 객체의 속성에 직접 값을 할당하는 행위였다. set함수를 할때는 불변성을 지켜야 한다. 즉 상태를 직접적으로 수정하지 않고, 새로운 상태를 생성하여 업데이트해야 한다는 것이다.

그래서 state자체를 빼버리고 set함수에 content: contents라고 할당하였다. 너무 boolean상태를 변화시키는 함수만 만들다 보니까 이런 함수는 어떻게 만들어야 되는지 몰랐었다ㅠㅜ

profile
이용자와 서비스를 하나로 만드는 개발자, Hermann입니다.

0개의 댓글