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
|
import { useRef } from 'react';
export const useApi = (authToken) => {
const apiRef = useRef(new Api());
apiRef.current.authToken = authToken;
return apiRef.current;
};
export class Api {
authToken = null;
makeRequest(url, method, body) {
const options = {};
if (method === 'POST' || method === 'PUT') {
options.body = JSON.stringify(body);
}
return fetch(url, {
method,
headers: {
Authorization: `Bearer ${this.authToken}`,
'Content-Type': 'application/json',
},
...options,
}).then((res) => res.json());
}
get(url) {
return this.makeRequest(url, 'GET');
}
post(url, body = {}) {
return this.makeRequest(url, 'POST', body);
}
put(url, body = {}) {
return this.makeRequest(url, 'PUT', body);
}
del(url) {
return this.makeRequest(url, 'DELETE');
}
}
|