1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-07-17 13:46:47 +02:00

Conditional swr (#2637)

This commit is contained in:
Mateusz Kwasniewski 2022-12-08 14:59:32 +01:00 committed by GitHub
parent 6bccffef97
commit 098755a9b4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,5 +1,4 @@
import useSWR, { BareFetcher, Key, SWRConfiguration, SWRResponse } from 'swr'; import useSWR, { BareFetcher, Key, SWRConfiguration, SWRResponse } from 'swr';
import { useEffect } from 'react';
export const useConditionalSWR = <Data = any, Error = any, T = boolean>( export const useConditionalSWR = <Data = any, Error = any, T = boolean>(
condition: T, condition: T,
@ -8,16 +7,11 @@ export const useConditionalSWR = <Data = any, Error = any, T = boolean>(
fetcher: BareFetcher<Data>, fetcher: BareFetcher<Data>,
options: SWRConfiguration = {} options: SWRConfiguration = {}
): SWRResponse<Data, Error> => { ): SWRResponse<Data, Error> => {
const result = useSWR( const result = useSWR(condition ? key : null, fetcher, options);
key,
(path: string) =>
condition ? fetcher(path) : Promise.resolve(fallback),
options
);
useEffect(() => { return {
result.mutate(); ...result,
}, [condition]); error: condition ? result.error : undefined,
data: condition ? result.data : fallback,
return result; };
}; };