Skip to content

Commit

Permalink
Fix with-i18n-rosetta example (#16023)
Browse files Browse the repository at this point in the history
* fix

* fix unstable useeffect dep

* FIxed lint issue

Co-authored-by: Luis Alvarez <[email protected]>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored Aug 10, 2020
1 parent 782d27e commit 4b2a825
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 22 deletions.
37 changes: 16 additions & 21 deletions examples/with-i18n-rosetta/lib/i18n.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,10 @@ export const I18nContext = createContext()
i18n.locale(defaultLanguage)

export default function I18n({ children, locale, lngDict }) {
const [activeDict, setActiveDict] = useState(() => lngDict)
const activeLocaleRef = useRef(locale || defaultLanguage)
const [, setTick] = useState(0)
const firstRender = useRef(true)

// for initial SSR render
if (locale && firstRender.current === true) {
firstRender.current = false
i18n.locale(locale)
i18n.set(locale, activeDict)
}

useEffect(() => {
if (locale) {
i18n.locale(locale)
i18n.set(locale, activeDict)
activeLocaleRef.current = locale
// force rerender
setTick((tick) => tick + 1)
}
}, [locale, activeDict])

const i18nWrapper = {
activeLocale: activeLocaleRef.current,
t: (...args) => i18n.t(...args),
Expand All @@ -44,13 +26,26 @@ export default function I18n({ children, locale, lngDict }) {
activeLocaleRef.current = l
if (dict) {
i18n.set(l, dict)
setActiveDict(dict)
} else {
setTick((tick) => tick + 1)
}
// force rerender to update view
setTick((tick) => tick + 1)
},
}

// for initial SSR render
if (locale && firstRender.current === true) {
firstRender.current = false
i18nWrapper.locale(locale, lngDict)
}

// when locale is updated
useEffect(() => {
if (locale) {
i18nWrapper.locale(locale, lngDict)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [lngDict, locale])

return (
<I18nContext.Provider value={i18nWrapper}>{children}</I18nContext.Provider>
)
Expand Down
2 changes: 1 addition & 1 deletion examples/with-i18n-rosetta/pages/[lng]/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const HomePage = () => {
<h2>{i18n.t('intro.text')}</h2>
<h3>{i18n.t('intro.description')}</h3>
<div>Current locale: {i18n.activeLocale}</div>
<Link href="/de">
<Link href="/[lng]" as="/de">
<a>Use client-side routing to change language to 'de'</a>
</Link>
</div>
Expand Down

0 comments on commit 4b2a825

Please sign in to comment.