PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 3.21.1
GiveWP – Donation Plugin and Fundraising Platform v3.21.1
4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 2.30.0 2.31.0 2.31.1 All 253 releases
give / src / Views / Components / ListTable / api.ts
api.ts
75 lines 2.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import useSWR from 'swr';
2 import lagData from './hooks/lagData';
3 import useFallbackAsInitial from '@givewp/components/ListTable/hooks/useFallbackAsInitial';
4
5 export default class ListTableApi {
6 private readonly apiRoot: string;
7 private controller: AbortController | null;
8 private readonly headers: {'X-WP-Nonce': string; 'Content-Type': string};
9 private readonly swrOptions;
10
11 constructor({apiNonce, apiRoot, preload = null}) {
12 this.controller = null;
13 this.apiRoot = apiRoot;
14 this.headers = {
15 'Content-Type': 'application/json',
16 'X-WP-Nonce': apiNonce,
17 };
18 this.swrOptions = {
19 use: [lagData],
20 onErrorRetry: (error, key, config, revalidate, {retryCount}) => {
21 //don't retry if we cancelled the initial request
22 if (error.name == 'AbortError') return;
23 if (retryCount >= 5) return;
24 const retryAfter = (retryCount + 1) * 500;
25 setTimeout(() => revalidate({retryCount}), retryAfter);
26 },
27 };
28 if (preload) {
29 this.swrOptions.fallbackData = preload;
30 this.swrOptions.use.push(useFallbackAsInitial);
31 }
32 }
33
34 fetchWithArgs = (endpoint, args, method = 'GET', signal = null) => {
35 const url = new URL(this.apiRoot + endpoint);
36 for (const [param, value] of Object.entries(args)) {
37 value !== '' && url.searchParams.set(param, value as string);
38 }
39 return fetch(url.href, {
40 method: method,
41 signal: signal,
42 headers: this.headers,
43 }).then((res) => {
44 if (!res.ok) {
45 throw new Error();
46 }
47 return res.json();
48 });
49 };
50
51 fetcher = (params) => {
52 if (this.controller instanceof AbortController) this.controller.abort();
53 this.controller = new AbortController();
54 return this.fetchWithArgs('', params, 'GET', this.controller.signal);
55 };
56
57 // SWR Fetcher
58 useListTable = ({page, perPage, sortColumn, sortDirection, locale, testMode, ...filters}) => {
59 const {data, error, mutate, isValidating} = useSWR(
60 {
61 page,
62 perPage,
63 sortColumn,
64 sortDirection,
65 locale,
66 testMode,
67 ...filters,
68 },
69 this.fetcher,
70 this.swrOptions
71 );
72 return {data, error, mutate, isValidating};
73 };
74 }
75