-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetchWithMsal.jsx
78 lines (65 loc) · 2.24 KB
/
useFetchWithMsal.jsx
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
import {
useState,
useCallback,
} from 'react';
import { InteractionType, PopupRequest } from '@azure/msal-browser';
import { useMsal, useMsalAuthentication } from "@azure/msal-react";
/**
* Custom hook to call a web API using bearer token obtained from MSAL
* @param {PopupRequest} msalRequest
* @returns
*/
const useFetchWithMsal = (msalRequest) => {
const { instance } = useMsal();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [data, setData] = useState(null);
const { result, error: msalError } = useMsalAuthentication(InteractionType.Popup, {
...msalRequest,
account: instance.getActiveAccount(),
redirectUri: '/redirect'
});
/**
* Execute a fetch request with the given options
* @param {string} method: GET, POST, PUT, DELETE
* @param {String} endpoint: The endpoint to call
* @param {Object} data: The data to send to the endpoint, if any
* @returns JSON response
*/
const execute = async (method, endpoint, data = null) => {
if (msalError) {
setError(msalError);
return;
}
if (result) {
try {
let response = null;
const headers = new Headers();
const bearer = `Bearer ${result.accessToken}`;
headers.append("Authorization", bearer);
if (data) headers.append('Content-Type', 'application/json');
let options = {
method: method,
headers: headers,
body: data ? JSON.stringify(data) : null,
};
setIsLoading(true);
response = await (await fetch(endpoint, options)).json();
setData(response);
setIsLoading(false);
return response;
} catch (e) {
setError(e);
setIsLoading(false);
throw e;
}
}
};
return {
isLoading,
error,
data,
execute: useCallback(execute, [result, msalError]), // to avoid infinite calls when inside a `useEffect`
};
};
export default useFetchWithMsal;