Skip to content

Commit

Permalink
♻️ refactor: Refactor antd locale file to useSWR
Browse files Browse the repository at this point in the history
  • Loading branch information
canisminor1990 committed Nov 7, 2023
1 parent 5b85bc2 commit 2e1cd7c
Showing 1 changed file with 6 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/layout/GlobalLayout/Locale.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ConfigProvider } from 'antd';
import defaultLocale from 'antd/locale/en_US';
import { PropsWithChildren, memo, useState } from 'react';
import useSWR from 'swr';

import { createI18nNext } from '@/locales/create';
import { useOnFinishHydrationGlobal } from '@/store/global';
Expand All @@ -12,7 +12,11 @@ interface LocaleLayoutProps extends PropsWithChildren {
}

const InnerLocale = memo<LocaleLayoutProps>(({ children, lang }) => {
const [locale, setLocale] = useState(defaultLocale);
const { data: locale } = useSWR(
lang,
async () =>
await import(`antd/locale/${lang?.includes('-') ? lang?.replace('-', '_') : 'en-US'}.js`),
);
const [i18n] = useState(createI18nNext(lang));

// if run on server side, init i18n instance everytime
Expand All @@ -27,19 +31,10 @@ const InnerLocale = memo<LocaleLayoutProps>(({ children, lang }) => {
});
}

const getLocale = async (localeName: string) => {
setLocale((await import(`antd/locale/${localeName}.js`)) as any);
};

useOnFinishHydrationGlobal((s) => {
if (s.settings.language === 'auto') {
switchLang('auto');
}

if (lang?.includes('-') && lang !== 'en-US') {
const localeName = lang?.replace('-', '_');
getLocale(localeName);
}
}, []);

return <ConfigProvider locale={locale}>{children}</ConfigProvider>;
Expand Down

0 comments on commit 2e1cd7c

Please sign in to comment.