-
Notifications
You must be signed in to change notification settings - Fork 67
/
usePatchRequest.tsx
38 lines (37 loc) · 1.29 KB
/
usePatchRequest.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { useClearCache } from '../useInvalidateCache/useInvalidateCache';
import { createRequestError } from './RequestError';
import { requestCommon } from './requestCommon';
/**
* Hook for making PATCH API requests
*
* - Returns a function that takes a url and body and returns the response body
* - Throws an RequestError if the response is not ok
* - Supports aborting the request on unmount
*/
export function usePatchRequest<RequestBody, ResponseBody>() {
const { clearCacheByKey } = useClearCache();
return async (url: string, body: RequestBody, signal?: AbortSignal) => {
const response: Response = await requestCommon({
url,
method: 'PATCH',
body,
signal,
});
if (!response.ok) {
throw await createRequestError(response);
}
clearCacheByKey(url);
switch (response.status) {
case 204:
return null as ResponseBody;
default:
if (response.headers.get('content-type')?.includes('application/json')) {
return (await response.json()) as ResponseBody;
} else if (response.headers.get('content-type')?.includes('text/plain')) {
return (await response.text()) as unknown as ResponseBody;
} else {
return (await response.blob()) as unknown as ResponseBody;
}
}
};
}