components
4 years ago
hooks
4 years ago
admin-donation-forms.module.scss
4 years ago
admin-donation-forms.tsx
4 years ago
api.ts
4 years ago
api.ts
54 lines
| 1 | import useSWR from 'swr'; |
| 2 | import lagData from './hooks/lagData'; |
| 3 | |
| 4 | declare global { |
| 5 | interface Window { |
| 6 | GiveDonationForms: {apiNonce: string; apiRoot: string}; |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | let controller = null; |
| 11 | const headers = { |
| 12 | 'Content-Type': 'application/json', |
| 13 | 'X-WP-Nonce': window.GiveDonationForms.apiNonce, |
| 14 | }; |
| 15 | |
| 16 | export const fetchWithArgs = (endpoint, args, method = 'GET', signal = null) => { |
| 17 | const url = new URL(window.GiveDonationForms.apiRoot + endpoint); |
| 18 | for (const [param, value] of Object.entries(args)) { |
| 19 | url.searchParams.set(param, value as string); |
| 20 | } |
| 21 | return fetch(url.href, { |
| 22 | method: method, |
| 23 | signal: signal, |
| 24 | headers: headers, |
| 25 | }).then((res) => { |
| 26 | if(!res.ok){ |
| 27 | throw new Error(); |
| 28 | } |
| 29 | return res.json(); |
| 30 | }); |
| 31 | } |
| 32 | |
| 33 | const Fetcher = (params) => { |
| 34 | if(controller instanceof AbortController) controller.abort(); |
| 35 | controller = new AbortController(); |
| 36 | return fetchWithArgs('', params, 'GET', controller.signal); |
| 37 | } |
| 38 | |
| 39 | // SWR Fetcher |
| 40 | export function useDonationForms({page, perPage, status, search}) { |
| 41 | const {data, error, isValidating} = useSWR({page, perPage, status, search}, Fetcher, { |
| 42 | use: [lagData], |
| 43 | onErrorRetry: (error, key, config, revalidate, { retryCount }) => { |
| 44 | //don't retry if we cancelled the initial request |
| 45 | if(error.name == 'AbortError') return; |
| 46 | if (retryCount >= 5) return |
| 47 | const retryAfter = (retryCount + 1) * 500; |
| 48 | setTimeout(() => revalidate({ retryCount }), retryAfter); |
| 49 | } |
| 50 | }); |
| 51 | |
| 52 | return {data, error, isValidating}; |
| 53 | } |
| 54 |