react
call api when parameter is not empty in SWR
펀치맨
2023. 5. 4. 09:52
✅ 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를 호출할수 있게된다 !
반응형