aboutsummaryrefslogtreecommitdiff
path: root/src/components/hooks/useCountryNames.ts
blob: 1ec9fc138eeff97be8f5738465e95ec6c146fe36 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useEffect, useState } from 'react';
import { httpGet } from '@/lib/fetch';
import enUS from '../../../public/intl/country/en-US.json';

const countryNames = {
  'en-US': enUS,
};

export function useCountryNames(locale: string) {
  const [list, setList] = useState(countryNames[locale] || enUS);

  async function loadData(locale: string) {
    const { data } = await httpGet(`${process.env.basePath || ''}/intl/country/${locale}.json`);

    if (data) {
      countryNames[locale] = data;
      setList(countryNames[locale]);
    } else {
      setList(enUS);
    }
  }

  useEffect(() => {
    if (!countryNames[locale]) {
      loadData(locale);
    } else {
      setList(countryNames[locale]);
    }
  }, [locale]);

  return { countryNames: list };
}