1. 문제상황

api Request Function 구현 중, 발생한 문제이다.

아래는 gifticon 전체 조회를 하는 함수이다.

export async function getMyGift() {
  const response = await fetch(`${ENDPOINT}/gift/mygifts?id=test1234`, {
    method: 'GET',
    headers: {
      Authorization: localStorage.getItem('access_token') as string,
    },
    credentials: 'include',
  });
  const result = await response.json();
  return result;
}

2. 왜 이런 문제가 발생했는가?

우리 페이지의 경우 이 함수를 두번 사용하는데. 다음과 같은 구조이다.

  1. profit/giftCard/myGiftCard/pages.tsx에서 해당 요청 함수를 실행해서 데이터를 받는다. (ssr, prefetch)
//import

export default async function Page() {
  const myGiftCard = await getMyGift();

  return (
    <>
      <Header title="내 기프티콘 조회" isFilterButton={false} isPrevButton />
      <div className="w-full h-full relative flex justify-center items-center flex-col">
        {(() => {
          if (myGiftCard.data.data.length === 0) {
            return <GiftCardEmptyRegistButton />; 
          }
          if (myGiftCard.data.data.length > 0) {
						//여기서 응답 데이터를 넘겨준다.
            return <MyGiftCardContainer myGiftCard={myGiftCard} />;
          }
          return <div>네트워크 에러!</div>;
        })()}
      </div>
      <div className="flex justify-center">
        <Navbar />
      </div>
    </>
  );
}
  1. profit/organisms/MyGiftCardContainer.tsx에서 요청을 통해 받은 데이터를 내려받는다. 또한, useQuery 내부에 initialData로써 저장한다.
'use client'

export default function MyGiftCardContainer({
  myGiftCard,
}: MyGiftContainerProps) {

  const { data, isLoading } = useQuery({
    queryKey: ['getMyGift'],
    queryFn: () => getMyGift(),
    initialData: myGiftCard,
  });

	//... 생략

}
  1. 이렇게 initialData로 저장할 시, 서버에서 받은 요청 데이터가 캐시에 저장되고, 데이터 갱신 전까지는 계속 저걸 쓸 것이다.