Merge pull request #2308 from payloadcms/fix/#2265

fix: cancels existing fetches if new fetches are started
This commit is contained in:
James Mikrut
2023-03-13 11:19:45 -07:00
committed by GitHub
2 changed files with 12 additions and 3 deletions

View File

@@ -12,7 +12,7 @@ export const requests = {
}
return fetch(`${url}${query}`, {
credentials: 'include',
headers: options.headers,
...options,
});
},

View File

@@ -43,12 +43,15 @@ const usePayloadAPI: UsePayloadAPI = (url, options = {}) => {
});
useEffect(() => {
const abortController = new AbortController();
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const response = await requests.get(`${url}${search}`, {
signal: abortController.signal,
headers: {
'Accept-Language': i18n.language,
},
@@ -62,8 +65,10 @@ const usePayloadAPI: UsePayloadAPI = (url, options = {}) => {
setData(json);
setIsLoading(false);
} catch (error) {
setIsError(true);
setIsLoading(false);
if (!abortController.signal.aborted) {
setIsError(true);
setIsLoading(false);
}
}
};
@@ -73,6 +78,10 @@ const usePayloadAPI: UsePayloadAPI = (url, options = {}) => {
setIsError(false);
setIsLoading(false);
}
return () => {
abortController.abort();
};
}, [url, locale, search, i18n.language]);
return [{ data, isLoading, isError }, { setParams }];