Skip to content

Commit

Permalink
Conditional swr (#2637)
Browse files Browse the repository at this point in the history
  • Loading branch information
kwasniew committed Dec 8, 2022
1 parent 6bccffe commit 098755a
Showing 1 changed file with 6 additions and 12 deletions.
@@ -1,5 +1,4 @@
import useSWR, { BareFetcher, Key, SWRConfiguration, SWRResponse } from 'swr';
import { useEffect } from 'react';

export const useConditionalSWR = <Data = any, Error = any, T = boolean>(
condition: T,
Expand All @@ -8,16 +7,11 @@ export const useConditionalSWR = <Data = any, Error = any, T = boolean>(
fetcher: BareFetcher<Data>,
options: SWRConfiguration = {}
): SWRResponse<Data, Error> => {
const result = useSWR(
key,
(path: string) =>
condition ? fetcher(path) : Promise.resolve(fallback),
options
);
const result = useSWR(condition ? key : null, fetcher, options);

useEffect(() => {
result.mutate();
}, [condition]);

return result;
return {
...result,
error: condition ? result.error : undefined,
data: condition ? result.data : fallback,
};
};

0 comments on commit 098755a

Please sign in to comment.