|
| 1 | +'use client' |
1 | 2 | import { Select } from '@chakra-ui/react'
|
2 | 3 | import { useLingui } from '@lingui/react/macro'
|
3 |
| -import { i18n } from "@lingui/core"; |
4 |
| -import { useRouter } from 'next/navigation' |
| 4 | +import { i18n } from '@lingui/core' |
| 5 | +import { useRouter, usePathname } from 'next/navigation' |
| 6 | +import { useState, useEffect } from 'react' |
5 | 7 |
|
6 | 8 | export const LanguageSwitcher = () => {
|
7 | 9 | const { t } = useLingui()
|
| 10 | + const router = useRouter() |
| 11 | + const pathname = usePathname() |
| 12 | + const [selectedValue, setSelectedValue] = useState('') |
8 | 13 |
|
9 |
| - async function dynamicActivate(event) { |
10 |
| - const locale = event.target.value |
11 |
| - const catalog = await import(`../locales/${locale}/messages.js`) |
12 |
| - i18n.load(locale, catalog.messages); |
13 |
| - i18n.activate(locale); |
| 14 | + async function changeLocale(event) { |
| 15 | + const localeString = event.target.value |
| 16 | + setSelectedValue(localeString) |
| 17 | + localStorage.setItem('locale', localeString) |
| 18 | + const catalog = await import(`../locales/${localeString}/messages.js`) |
| 19 | + i18n.load(localeString, catalog.messages) |
| 20 | + i18n.activate(localeString) |
| 21 | + router.push(pathname, { locale: localeString }) |
14 | 22 | }
|
| 23 | + |
| 24 | + useEffect(() => { |
| 25 | + const storedLocale = localStorage.getItem('locale') |
| 26 | + if (storedLocale && storedLocale !== router.locale) { |
| 27 | + changeLocale({ target: { value: storedLocale } }) |
| 28 | + } |
| 29 | + }, []) |
15 | 30 | return (
|
16 |
| - <Select variant='flushed' size='xs' defaultValue="en" onChange={dynamicActivate}> |
| 31 | + <Select |
| 32 | + name='selectedLocale' |
| 33 | + variant='flushed' |
| 34 | + size='xs' |
| 35 | + value={selectedValue} |
| 36 | + onChange={changeLocale} |
| 37 | + > |
17 | 38 | <option value='en'>{t`English`}</option>
|
18 | 39 | <option value='es'>{t`Spanish`}</option>
|
19 | 40 | <option value='pt'>{t`Portuguese`}</option>
|
|
0 commit comments