umami/hooks/useCountryNames.js

35 lines
782 B
JavaScript
Raw Normal View History

2020-10-01 01:27:27 +02:00
import { useState, useEffect } from 'react';
2020-10-01 07:34:16 +02:00
import { useRouter } from 'next/router';
2022-08-29 05:20:54 +02:00
import { get } from 'next-basics';
2022-03-19 03:17:23 +01:00
import enUS from 'public/intl/country/en-US.json';
2020-10-01 01:27:27 +02:00
const countryNames = {
'en-US': enUS,
};
export default function useCountryNames(locale) {
const [list, setList] = useState(countryNames[locale] || enUS);
2020-10-01 07:34:16 +02:00
const { basePath } = useRouter();
2020-10-01 01:27:27 +02:00
async function loadData(locale) {
2023-04-09 01:31:21 +02:00
const { data } = await get(`${basePath}/intl/country/${locale}.json`);
2020-10-01 01:27:27 +02:00
if (data) {
2020-10-01 01:27:27 +02:00
countryNames[locale] = data;
setList(countryNames[locale]);
} else {
setList(enUS);
}
}
useEffect(() => {
if (!countryNames[locale]) {
loadData(locale);
} else {
setList(countryNames[locale]);
}
}, [locale]);
return list;
}