본문 바로가기

react

call api when parameter is not empty in SWR

✅ Conditional Fetching

useSWR 인자인 key 값이나, fetcher 파라미터에 null을 주면 swr는 fetch를 하지 않는다.

 

 

mutate 같이 적용하기

export const getMall = (token: string) => {
  const { data, mutate } = useSWRImmutable('/mall', (url) => (token ? fetcher(url, null, token) : null));

  return {
    mall: data?.result as MallProps,
    mutate,
  };
};

getMall 함수에서 token 값이 없으면 fetch를 진행하지 않는다.

getMall 함수를 호출하는 곳에서 token 을 얻으면 다시 mutate 를 통해서 /mall api를 호출할수 있게된다 !

 

 

https://swr.vercel.app/docs/conditional-fetching

반응형