UNPKG

1.57 kBPlain TextView Raw
1/* eslint-disable @typescript-eslint/no-unsafe-assignment */
2import Axios from 'axios';
3import type { Dispatch, SetStateAction } from 'react';
4import type { AxiosCacheHooksOptions } from './options';
5import type { ApiCall, State } from './types';
6
7export 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 // Successful response
17 (response) => {
18 const rid = options.hashGenerator(response, undefined);
19
20 // Request never had data before or there is new data available
21 if (state.rid !== rid) {
22 setState({ loading: false, data: response.data, response, rid });
23 }
24 },
25
26 // Error response
27 (error) => {
28 // Request was aborted because the component was unmounted
29 // Update the state now will throw a "Called SetState()
30 // on an Unmounted Component" error.
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 // This avoids a unhandled promise exception in case of an unhandled
43 // error thrown above.
44 .catch((error) => {
45 console.error('Unknown error thrown by axios cache hooks', error);
46 })
47 );
48}