Skip to content

Commit

Permalink
fix(next-international): don't load locale client-side if SSR/SSGed (#39
Browse files Browse the repository at this point in the history
)
  • Loading branch information
QuiiBz authored Oct 17, 2022
1 parent 386bc09 commit d7e1c8d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
2 changes: 1 addition & 1 deletion examples/next/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
reactStrictMode: false,
swcMinify: true,
i18n: {
locales: ['en', 'fr'],
Expand Down
2 changes: 1 addition & 1 deletion examples/next/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,6 @@ const Home = () => {
};

// Comment this to disable SSR of initial locale
export const getStaticProps: GetStaticProps = getLocaleProps();
// export const getStaticProps: GetStaticProps = getLocaleProps();

export default Home;
26 changes: 19 additions & 7 deletions packages/next-international/src/i18n/create-i18n-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { Context, ReactElement, ReactNode, useEffect, useState } from 'react';
import React, { Context, ReactElement, ReactNode, useCallback, useEffect, useRef, useState } from 'react';
import type { LocaleContext, Locales } from '../types';
import type { BaseLocale } from 'international-types';
import { useRouter } from 'next/router';
Expand All @@ -23,6 +23,7 @@ export function createI18nProvider<Locale extends BaseLocale>(
}: I18nProviderProps<Locale>) {
const { locale, defaultLocale, locales: nextLocales } = useRouter();
const [clientLocale, setClientLocale] = useState<Locale>();
const initialLoadRef = useRef(true);

useEffect(() => {
function checkConfigMatch([first, second]: [[string, string[]], [string, string[]]]) {
Expand All @@ -42,15 +43,26 @@ export function createI18nProvider<Locale extends BaseLocale>(
checkConfigMatch([nextConfig, createI18n]);
}, [nextLocales]);

useEffect(() => {
if (!locale || !defaultLocale) {
return;
}

const loadLocale = useCallback((locale: string) => {
locales[locale]().then(content => {
setClientLocale(content.default as Locale);
});
}, [locale, defaultLocale]);
}, []);

useEffect(() => {
// Initial page load
// Load locale if no baseLocale provided from getLocaleProps
if (!baseLocale && locale && initialLoadRef.current) {
loadLocale(locale);
}

// Subsequent locale change
if (locale && !initialLoadRef.current) {
loadLocale(locale);
}

initialLoadRef.current = false;
}, [baseLocale, loadLocale, locale]);

if (!locale || !defaultLocale) {
return error(`'i18n.defaultLocale' not defined in 'next.config.js'`);
Expand Down

0 comments on commit d7e1c8d

Please sign in to comment.