SWR useSWRInfinite fallback 처리하는 방법

남양주개발자

·

2022. 4. 30. 19:46

728x90
반응형

SWR useSWRInfinite fallback 처리하는 방법

Next.js에서 SWR을 활용할 때 기본 데이터를 활용해서 Pre-rendering을 처리해야 할 경우가 있습니다. 아래와 같이 useSWRInfinite에서 fallback 데이터를 처리하려고 했으나 Pre-rendering가 되지 않았습니다. fallbackData로 처리하려고 했지만 예상과는 다른 동작으로 인해 fallback으로 처리하는 방법을 좀 더 고민했어야 했습니다.

  const { data, error, isValidating, mutate, size, setSize } = useSWRInfinite(
    getKey,
    fetchFinder,
    {
    	fallback: {
        	"hello": []
        }
    }
  );

아래와 같이 useSWRConfig를 통해 캐시된 key들을 살펴보는 와중에 useSWRInfinite의 경우 캐시키로 $inf$를 가지고 있음을 확인할 수 있었습니다.

const { fallback, cache } = useSWRConfig();
console.log(cache);

getStaticProps에서 fallback props를 만들어줄 때 아래와 같이 $inf$ 플래그를 넣어줌으로써 깔끔하게 해결 완료!

export const getStaticProps: GetStaticProps<{
  dataSource: MainModule[];
}> = async (context) => {
  const FINDER_FETCH_KEY = `$inf$/api/finder/{test}?${qs.stringify({
    start: 0,
    rows: 10,
    testObj: [
      {
        value: sample[0].name,
      },
    ],
  })}`;

  return {
    props: {
      fallback: {
        "/api/config": config,
        [FINDER_FETCH_KEY]: [finderResult],
      },
    },
    revalidate: 600,
  };
};

++ 개선안

swr/infinite unstable_serialize를 활용하면 위에서 넣엇던 $inf$ 플래그가 자동으로 들어갑니다.

import { unstable_serialize } from "swr/infinite";

 

const finderFallback = finderFetchKeyList.reduce(
(acc, key, i) =>
  Object.assign({}, acc, {
    [unstable_serialize(() => key)]: [finderResult[i]],
  }),
{},
);
728x90
반응형
그리드형

💖 저자에게 암호화폐로 후원하기 💖

아이콘을 클릭하면 지갑 주소가자동으로 복사됩니다