1
0
mirror of https://github.com/Sonarr/Sonarr.git synced 2026-04-26 22:56:23 -04:00

Update React and add React Query

This commit is contained in:
Mark McDowall
2024-11-23 20:20:36 -08:00
parent a90866a73e
commit 4491df3ae7
7 changed files with 138 additions and 41 deletions
+56
View File
@@ -0,0 +1,56 @@
import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
interface QueryOptions {
url: string;
headers?: HeadersInit;
}
const absUrlRegex = /^(https?:)?\/\//i;
const apiRoot = window.Sonarr.apiRoot;
function isAbsolute(url: string) {
return absUrlRegex.test(url);
}
function getUrl(url: string) {
return apiRoot + url;
}
function useApiQuery<T>(options: QueryOptions) {
const { url, headers } = options;
const final = useMemo(() => {
if (isAbsolute(url)) {
return {
url,
headers,
};
}
return {
url: getUrl(url),
headers: {
...headers,
'X-Api-Key': window.Sonarr.apiKey,
},
};
}, [url, headers]);
return useQuery({
queryKey: [final.url],
queryFn: async () => {
const result = await fetch(final.url, {
headers: final.headers,
});
if (!result.ok) {
throw new Error('Failed to fetch');
}
return result.json() as T;
},
});
}
export default useApiQuery;