1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00

move fetchWithTimeout to ~/util for re-use [skip ci]

This commit is contained in:
checktheroads
2020-12-29 17:22:07 -07:00
parent d0b78ae69f
commit 5aabbab4bb
2 changed files with 28 additions and 27 deletions

View File

@@ -1,36 +1,10 @@
import { useQuery } from 'react-query';
import { useConfig } from '~/context';
import { fetchWithTimeout } from '~/util';
import type { TFormQuery } from '~/types';
import type { TUseLGQueryFn } from './types';
/**
* Fetch Wrapper that incorporates a timeout via a passed AbortController instance.
*
* Adapted from: https://lowmess.com/blog/fetch-with-timeout
*/
export async function fetchWithTimeout(
uri: string,
options: RequestInit = {},
timeout: number,
controller: AbortController,
): Promise<Response> {
/**
* Lets set up our `AbortController`, and create a request options object that includes the
* controller's `signal` to pass to `fetch`.
*/
const { signal = new AbortController().signal, ...allOptions } = options;
const config = { ...allOptions, signal };
/**
* Set a timeout limit for the request using `setTimeout`. If the body of this timeout is
* reached before the request is completed, it will be cancelled.
*/
setTimeout(() => {
controller.abort();
}, timeout);
return await fetch(uri, config);
}
export function useLGQuery(query: TFormQuery) {
const { request_timeout, cache } = useConfig();
const controller = new AbortController();