[TIL] 내일배움캠프 React 과정 2024.07.29

김형빈·2024년 7월 29일
0

내일배움캠프

목록 보기
69/81
post-thumbnail

오늘의 한 일

  • Work Connect
    • 홈 페이지 기능 구현
    • 프로필 페이지 일부 스타일 구현

홈 페이지 데이터 다루기

문제 상황

  • 홈페이지에서 전역으로 관리되고 있는 workspaceUserId를 사용하여 workspaceUser의 정보를 불러와야한다.

문제 코드

const Homepage = () => {
   const { workspaceUserId, workspaceList } = useUserStore(
    useShallow((state) => ({
      workspaceUserId: state.workspaceId,
      workspaceList: state.workspaceList
    }))
  );
  const { workspaceUser } = useWorkspaceUser(workspaceUserId); // Type 'null' is not assignable to type type 'string'
  if (!workspaceUser) return;
  return ...
};

export default Homepage;
  • workspaceUserId는 초기에 null 값이기에 workspaceUser를 제대로 호출하지 못한다는 문제가 있다.

문제 해결 방안1

const Homepage = () => {
   const { workspaceUserId, workspaceList } = useUserStore(
    useShallow((state) => ({
      workspaceUserId: state.workspaceId,
      workspaceList: state.workspaceList
    }))
  );
  if (!workspaceUserId) return;
  const { workspaceUser } = useWorkspaceUser(workspaceUserId);
  if (!workspaceUser) return;
  return ...
};

export default Homepage;
  • early return 패턴을 도입한다.
  • userId 값이 존재할 때에만 useWorkspaceUser 훅을 호출하게 된다.

해결 방안의 결과

  • hook 앞에 return 문을 사용하게 되어서 오류가 발생하였다.
  • hook은 어떤 경우에도 조건부로 호출되어서는 안된다!
profile
The secret of getting ahead is getting started.

0개의 댓글