This repository was archived by the owner on Sep 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFetch.ts
More file actions
148 lines (120 loc) · 3.26 KB
/
useFetch.ts
File metadata and controls
148 lines (120 loc) · 3.26 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import { APIFetchOptions } from '@wordpress/api-fetch';
const { __ } = wp.i18n;
wp.apiFetch.setFetchHandler( async ( nextOptions ) => {
const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
let { body, headers } = nextOptions;
// Merge explicitly-provided headers with default values.
headers = { Accept: 'application/json, */*;q=0.1', ...headers };
// The `data` property is a shorthand for sending a JSON body.
if ( data ) {
body = JSON.stringify( data );
headers[ 'Content-Type' ] = 'application/json';
}
try {
const response = await window.fetch(
// fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed
url || path || window.location.href,
{
credentials: 'include',
...remainingOptions,
body,
headers,
}
);
if ( response.status < 200 || response.status >= 300 ) {
throw response;
}
if ( ! parse ) return response;
if ( response.status === 204 ) return null;
if ( ! response.json ) throw response;
return await response.json();
} catch ( response ) {
if ( parse ) {
const invalidJsonError = {
code: 'invalid_json',
message: __( 'The response is not a valid JSON response.' ),
};
if ( response instanceof Error ) {
throw {
code: 'fetch_error',
message: `(${ response.name }) ${ response.message }`,
};
}
if ( ! response || ! response.json ) {
throw invalidJsonError;
}
throw await ( response as Response ).json().catch( () => {
throw invalidJsonError;
} );
}
throw response;
}
} );
export function useFetch< Result >(
options: APIFetchOptions,
dependencies: ReadonlyArray< any >
) {
const ref = wp.element.useRef( options );
wp.element.useEffect( () => {
ref.current = options;
}, [ options ] );
return baseFetch< Result >( ref, dependencies );
}
function baseFetch< Result >(
ref: React.MutableRefObject< APIFetchOptions >,
dependencies: ReadonlyArray< any >
) {
const [ refetch, setRefetch ] = wp.element.useState< boolean >( false );
const [ status, setStatus ] = wp.element.useState( 'idle' );
const [ data, setData ] = wp.element.useState< Result >();
const [ error, setError ] = wp.element.useState< unknown >();
wp.element.useEffect( () => {
if ( ! ref.current ) return;
const abort = new AbortController();
const fetchData = async () => {
setStatus( 'loading' );
try {
const result = await wp.apiFetch< Result >( {
signal: abort.signal,
...ref.current,
} );
setData( result );
setStatus( 'success' );
} catch ( e: unknown ) {
setError( e );
setStatus( 'error' );
}
};
fetchData();
return () => abort.abort();
}, [ ...dependencies, refetch ] );
return {
status,
data,
error,
refetch: wp.element.useCallback( () => {
setRefetch( ( prev ) => ! prev );
}, [] ),
} as const;
}
export function usePostFetch< Result >(
options: APIFetchOptions,
dependencies: ReadonlyArray< any >
) {
const ref = wp.element.useRef< APIFetchOptions >( null );
const result = baseFetch< Result >( ref, [ ...dependencies ] );
return {
...result,
post: wp.element.useCallback(
( data: any ) => {
ref.current = {
method: 'POST',
data,
...options,
};
result.refetch();
},
[ options ]
),
} as const;
}