1 |
|
2 | import Axios from 'axios';
|
3 | import type { Dispatch, SetStateAction } from 'react';
|
4 | import type { AxiosCacheHooksOptions } from './options';
|
5 | import type { ApiCall, State } from './types';
|
6 |
|
7 | export function executeApiCall<Data, Args extends unknown[]>(
|
8 | apiCall: ApiCall<Data, Args>,
|
9 | args: Args,
|
10 | [state, setState]: [State<Data>, Dispatch<SetStateAction<State<Data>>>],
|
11 | options: AxiosCacheHooksOptions
|
12 | ): Promise<void> {
|
13 | return (
|
14 | apiCall(...args)
|
15 | .then(
|
16 |
|
17 | (response) => {
|
18 | const rid = options.hashGenerator(response, undefined);
|
19 |
|
20 |
|
21 | if (state.rid !== rid) {
|
22 | setState({ loading: false, data: response.data, response, rid });
|
23 | }
|
24 | },
|
25 |
|
26 |
|
27 | (error) => {
|
28 |
|
29 |
|
30 |
|
31 | if (Axios.isCancel(error)) {
|
32 | return;
|
33 | }
|
34 |
|
35 | const rid = options.hashGenerator(undefined, error);
|
36 |
|
37 | if (rid !== state.rid) {
|
38 | setState({ loading: false, error, rid });
|
39 | }
|
40 | }
|
41 | )
|
42 |
|
43 |
|
44 | .catch((error) => {
|
45 | console.error('Unknown error thrown by axios cache hooks', error);
|
46 | })
|
47 | );
|
48 | }
|