[ Warning ] Cannot update a component (`A`) while rendering a different component (`B`). To locate the bad setState() call inside `B`

honney·2024년 10월 22일

What is problem?

다른 컴포넌트 ('B')를 렌더링 하는 동안 컴포넌트('A')를 업데이트 할 수 없다.

출처 : https://github.com/facebook/react/issues/18178#issuecomment-595846312

Why did the problem occur in my code?

'use client';

import Loading from '@/app/loading';
import { LoginUserDataType } from '@/utils/common/cookies';
import { useRouter } from 'next/navigation';


export default function LoginContainer({ loginUserData }: { loginUserData?: LoginUserDataType }) {
  const router = useRouter();

  if (!loginUserData) {
    alert('카카오 로그인 에러');
    router.push('/');
  }


  fetch('http://localhost:8080/api/set-cookies', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(loginUserData),
  });

  router.push('/wishes');

  return <Loading />;
}

await 키워드를 붙이지 않아 코드가 비동기로 실행되다보니 wishes페이지로 이동하여 wishes페이지의 컴포넌트를 렌더링 하게 된다. 그때에 fetch를 통해 cookies의 상태를 업데이트 해주기 때문에 다믕과 같은 경고가 발생하게 되었다.

How to fix it?

'use client';

import Loading from '@/app/loading';
import { LoginUserDataType } from '@/utils/common/cookies';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

export default function LoginContainer({ loginUserData }: { loginUserData?: LoginUserDataType }) {
  const router = useRouter();

  if (!loginUserData) {
    alert('카카오 로그인 에러');
    router.push('/');
  }

  //1. useEffect를 통해 로딩 컴포넌트가 그려진 이후에 함수를 실행
  useEffect(() => { 
    fetch('http://localhost:8080/api/set-cookies', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(loginUserData),
    }).then(() => {
      router.push('/wishes');
    });//2. fetch의 실행이 마치고 wishes페이지로 이동하게 수정
  }, []);


  return <Loading />;
}

굉장히 초보적인 실수였던거 같다..ㅎㅎ

profile
보이지 않은 것을 보이게 할 때 기쁨을 느낍니다

0개의 댓글