-
Notifications
You must be signed in to change notification settings - Fork 687
/
Copy pathuseRestApi.js
47 lines (40 loc) · 1.49 KB
/
useRestApi.js
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
import { useCallback, useMemo } from 'react';
import * as RestApi from '../RestApi';
import { useRestResponse } from './useRestResponse';
const { request } = RestApi.Magento2;
/**
* Exposes an API for sending REST calls and handling their responses.
*
* @param {String} endpoint - A Magento 2 REST API endpoint.
* Ex: /rest/V1/carts/mine/estimate-shipping-methods
*/
export const useRestApi = endpoint => {
const [restResponseState, restResponseApi] = useRestResponse();
const { receiveError, receiveResponse, setLoading } = restResponseApi;
// Define a callback that sends a request
// either as an effect or in response to user interaction.
const sendRequest = useCallback(
async ({ options }) => {
// setLoading to true before making the call.
// There is no need to setLoading to false after because
// both receiveResponse and receiveError handle that.
setLoading(true);
try {
const response = await request(endpoint, options);
receiveResponse(response);
} catch (error) {
// error is of type M2ApiResponseError here.
receiveError(error.baseMessage);
}
},
[endpoint, receiveError, receiveResponse, setLoading]
);
const api = useMemo(
() => ({
...restResponseApi,
sendRequest
}),
[restResponseApi, sendRequest]
);
return [restResponseState, api];
};