| 1 |
import { PATTERNS_HOST } from '@constants'; |
| 2 |
import useSWRInfinite from 'swr/infinite'; |
| 3 |
|
| 4 |
const fetcher = (url) => fetch(url).then((res) => res.json()); |
| 5 |
|
| 6 |
export const usePatterns = (incomingParams) => { |
| 7 |
const params = { |
| 8 |
siteType: undefined, |
| 9 |
category: undefined, |
| 10 |
wpVersion: window.extSharedData.wpVersion, |
| 11 |
lang: window.extSharedData.wpLanguage || null, |
| 12 |
showLocalizedCopy: window.extSharedData.showLocalizedCopy || null, |
| 13 |
...incomingParams, |
| 14 |
}; |
| 15 |
|
| 16 |
const getKey = (pageIndex, previousPageData) => { |
| 17 |
if (!params.category) return null; |
| 18 |
if (previousPageData && !previousPageData.length) return null; |
| 19 |
|
| 20 |
const urlParams = new URLSearchParams({ page: pageIndex + 1 }); |
| 21 |
|
| 22 |
Object.entries(params) |
| 23 |
.filter(([, value]) => value !== undefined) |
| 24 |
.forEach(([key, value]) => { |
| 25 |
urlParams.append(key, value); |
| 26 |
}); |
| 27 |
|
| 28 |
return `${PATTERNS_HOST}/api/patterns?${urlParams.toString()}`; |
| 29 |
}; |
| 30 |
|
| 31 |
const { data, error, isLoading, isValidating, mutate, size, setSize } = |
| 32 |
useSWRInfinite(getKey, fetcher, { |
| 33 |
initialSize: 2, |
| 34 |
revalidateFirstPage: false, |
| 35 |
revalidateIfStale: false, |
| 36 |
revalidateOnFocus: false, |
| 37 |
revalidateOnReconnect: false, |
| 38 |
}); |
| 39 |
|
| 40 |
return { |
| 41 |
data, |
| 42 |
error, |
| 43 |
isLoading, |
| 44 |
isValidating, |
| 45 |
mutate, |
| 46 |
size, |
| 47 |
setSize, |
| 48 |
}; |
| 49 |
}; |
| 50 |
|