forked from next-multilingual/next-multilingual
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
202 lines (185 loc) · 6.41 KB
/
index.tsx
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import {
getActualDefaultLocale, getActualLocale, getActualLocales, getCookieLocale, getPreferredLocale,
normalizeLocale, ResolvedLocaleServerSideProps, setCookieLocale
} from 'next-multilingual';
import { getTitle, useMessages } from 'next-multilingual/messages';
import { useRouter } from 'next/router';
import { useEffect, useRef, useState } from 'react';
import Layout from '@/layout';
import { useFruitsMessages } from '../messages/useFruitsMessages';
import styles from './index.module.css';
import type { GetServerSideProps, NextPage } from 'next';
const Home: NextPage<ResolvedLocaleServerSideProps> = ({ resolvedLocale }) => {
const router = useRouter();
const { locales, defaultLocale, basePath } = router;
// Overwrite the locale with the resolved locale.
router.locale = resolvedLocale;
setCookieLocale(router.locale);
// Load the messages in the correct locale.
const messages = useMessages();
const fruitsMessages = useFruitsMessages();
// Counter used for ICU MessageFormat example.
const [count, setCount] = useState(0);
// Localized API.
const [apiError, setApiError] = useState<DOMException | null>(null);
const [isApiLoaded, setApiIsLoaded] = useState(false);
const [apiMessage, setApiMessage] = useState('');
const controllerRef = useRef<AbortController | null>();
useEffect(() => {
if (controllerRef.current) {
/**
* This controller allows to abort "queued" requests. Without this, someone could switch language
* and an API response in the wrong language could be displayed. Every time `abort` called, it
* will trigger an error which we ignore below.
*/
controllerRef.current.abort();
}
const controller = new AbortController();
controllerRef.current = controller;
setApiIsLoaded(false);
const requestHeaders: HeadersInit = new Headers();
requestHeaders.set('Accept-Language', normalizeLocale(router.locale as string));
fetch(`${basePath}/api/hello`, {
headers: requestHeaders,
signal: controllerRef.current?.signal,
})
.then((result) => result.json())
.then(
(result) => {
setApiIsLoaded(true);
setApiMessage(result.message);
controllerRef.current = null;
},
(apiError: DOMException) => {
if (apiError.name !== 'AbortError') {
// Only show valid errors.
setApiIsLoaded(true);
setApiError(apiError);
}
}
);
}, [router.locale, basePath]);
function showApiMessage(): JSX.Element {
if (apiError) {
return (
<>
{messages.format('apiError')}
{apiError.message}
</>
);
} else if (!isApiLoaded) {
return <>{messages.format('apiLoading')}</>;
} else {
return <>{apiMessage}</>;
}
}
return (
<Layout title={getTitle(messages)}>
<h1 className={styles.headline}>{messages.format('headline')}</h1>
<div>
<h2 className={styles.subHeader}>{messages.format('subHeader')}</h2>
<table className={styles.table}>
<thead>
<tr>
<th>{messages.format('columnInformation')}</th>
<th>{messages.format('columnNextJs')}</th>
<th>{messages.format('columnActual')}</th>
</tr>
</thead>
<tbody>
<tr>
<td>{messages.format('rowDefaultLocale')}</td>
<td>{normalizeLocale(defaultLocale as string)}</td>
<td>{normalizeLocale(getActualDefaultLocale(locales, defaultLocale))}</td>
</tr>
<tr>
<td>{messages.format('rowConfiguredLocales')}</td>
<td>{locales?.map((locale) => normalizeLocale(locale)).join(', ')}</td>
<td>
{getActualLocales(locales, defaultLocale)
?.map((locale) => normalizeLocale(locale))
.join(', ')}
</td>
</tr>
</tbody>
</table>
<br />
<div id="shared-messages">
<h2>{messages.format('sharedHeader')}</h2>
<div>
{messages.format('sharedList')}
<i>
{fruitsMessages
.getAll()
.map((message) => message.format())
.join(', ')}
</i>
</div>
<div>
{messages.format('sharedDropDown')}
<select>
{fruitsMessages.getAll().map((message) => (
<option key={message.format()}>{message.format()}</option>
))}
</select>
</div>
</div>
<br />
<div>
<h2>{messages.format('mfHeader')}</h2>
<fieldset className={styles.mfExample}>
<legend>{messages.format('mfUsing')}</legend>
{messages.format('mfPlural')}
</fieldset>
<p id="plural-messages-output">{messages.format('mfPlural', { count })}</p>
<button
id="plural-messages-add"
onClick={() => setCount(count + 1)}
title={messages.format('mfAddCandy')}
>
➕🍭
</button>
<button
id="plural-messages-subtract"
onClick={() => {
if (count > 0) setCount(count - 1);
}}
title={messages.format('mfRemoveCandy')}
>
➖🍭
</button>
</div>
<br />
<div>
<h2>{messages.format('apiHeader')}</h2>
<div id="api-response">{showApiMessage()}</div>
</div>
</div>
</Layout>
);
};
export default Home;
export const getServerSideProps: GetServerSideProps<ResolvedLocaleServerSideProps> = async (
nextPageContext
) => {
const { req, locale, locales, defaultLocale } = nextPageContext;
const actualLocales = getActualLocales(locales, defaultLocale);
const actualDefaultLocale = getActualDefaultLocale(locales, defaultLocale);
const cookieLocale = getCookieLocale(nextPageContext, actualLocales);
let resolvedLocale = getActualLocale(locale, defaultLocale, locales);
// When Next.js tries to use the default locale, try to find a better one.
if (locale === defaultLocale) {
resolvedLocale = cookieLocale
? cookieLocale
: getPreferredLocale(
req.headers['accept-language'],
actualLocales,
actualDefaultLocale
).toLowerCase();
}
return {
props: {
resolvedLocale,
},
};
};