I am using useSWR.
Sometimes the application fetches data twice, even though none of the fetchOptions
have changed.
My code:
export function ApiProvider({
method = "GET",
path, // string
query, // type Query = Record<string, string>;
cacheKey = [path, query],
enabled, // boolean
name,
previewData,
children,
refetchIfStale = true,
refetchOnWindowFocus = false,
refetchOnReconnect = false,
retryOnError = true,
alertOnError = true,
useNodejsApi = true,
transformResponse = defaultResponseTransform,
onLoad,
onError,
}: ApiProviderProps) {
const fetchOptions: FetchApiOptions = { method, path, query, useNodejsApi };
const [debouncedFetchOptions] = useDebounce(fetchOptions, 200, {
leading: true,
}); // 1. What I tried
const shouldRetry = useShouldRetry();
const debouncedFetchet = useDebouncedCallback(
(options: FetchApiOptions) =>
fetchApi(options).then((data: unknown) =>
transformResponse(data, fetchOptions),
),
200,
{
leading: true,
},
); // 2. What I tried
const fetcher = (options: FetchApiOptions) =>
fetchApi(options).then((data: unknown) =>
transformResponse(data, fetchOptions),
);
const response = useSWR(
enabled ? cacheKey : null,
() => {
return fetcher(debouncedFetchOptions);
}, // 1. with debounced options
() => {
return debouncedFetcher(fetchOptions);
}, // 2. with debounced fetcher
() => {
return fetcher(fetchOptions);
},
{
use: [swrLaggyMiddleware],
revalidateIfStale: refetchIfStale,
revalidateOnFocus: refetchOnWindowFocus,
revalidateOnReconnect: refetchOnReconnect,
shouldRetryOnError: retryOnError && shouldRetry,
},
);
const mockedResponse = useMockedResponse({
response,
editorMode,
previewData,
transformResponse,
fetchOptions,
});
useOnLoad({ onLoad, data: mockedResponse.data });
useOnError({
onError,
error: mockedResponse.error,
alertOnError,
});
return (
<DataProvider name={name} data={mockedResponse}>
{children}
</DataProvider>
);
}
To prevent this, I decided to use a “use-debounce” library
. However, I completely do not know how I should combine it with useSWR. I tried debounce options by using useDebounce. I tried to debounce the whole fetch function. Nothing helped. Maybe I’m doing something wrong?
Maybe it is possible to prevent fetching again if the options have not changed without using debounce?
Could you suggest something? Thank You in advance.
ddosmiko is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.