| 1 |
import { useState } from '@wordpress/element'; |
| 2 |
import { PATTERNS_HOST } from '@constants'; |
| 3 |
import useSWRImmutable from 'swr/immutable'; |
| 4 |
|
| 5 |
const fetcher = async () => { |
| 6 |
const urlParams = new URLSearchParams({ |
| 7 |
wpVersion: window.extSharedData.wpVersion || null, |
| 8 |
lang: window.extSharedData.wpLanguage || null, |
| 9 |
}); |
| 10 |
return await fetch( |
| 11 |
`${PATTERNS_HOST}/api/categories?${urlParams.toString()}`, |
| 12 |
).then((res) => res.json()); |
| 13 |
}; |
| 14 |
|
| 15 |
export const useCategories = () => { |
| 16 |
const [errorCount, setErrorCount] = useState(0); |
| 17 |
const lang = window.extSharedData?.wpLanguage ?? 'en_US'; |
| 18 |
const { data, error, isLoading } = useSWRImmutable( |
| 19 |
`categories-${lang}`, |
| 20 |
fetcher, |
| 21 |
{ |
| 22 |
onError: () => setErrorCount((prev) => prev + 1), |
| 23 |
onSuccess: () => setErrorCount(0), |
| 24 |
}, |
| 25 |
); |
| 26 |
return { |
| 27 |
data, |
| 28 |
errorCount: errorCount > 1 ? errorCount : error ? 1 : 0, |
| 29 |
isLoading, |
| 30 |
}; |
| 31 |
}; |
| 32 |
|