-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathintl.js
79 lines (70 loc) · 1.97 KB
/
intl.js
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
/* eslint-disable import/prefer-default-export */
import { IntlProvider } from 'react-intl';
import {
SET_LOCALE_START,
SET_LOCALE_SUCCESS,
SET_LOCALE_ERROR,
} from '../constants';
import queryIntl from './intl.graphql';
function getIntlFromState(state) {
const intl = (state && state.intl) || {};
const { initialNow, locale, messages } = intl;
const localeMessages = (messages && messages[locale]) || {};
const provider = new IntlProvider({
initialNow,
locale,
messages: localeMessages,
defaultLocale: 'en-US',
});
return provider.getChildContext().intl;
}
export function getIntl() {
return (dispatch, getState) => getIntlFromState(getState());
}
export function setLocale({ locale }) {
return async (dispatch, getState, { client, history }) => {
dispatch({
type: SET_LOCALE_START,
payload: {
locale,
},
});
try {
// WARNING !!
// do not use client.networkInterface except you want skip Apollo store
// use client.query if you want benefit from Apollo caching mechanisms
const { data } = await client.query({
query: queryIntl,
variables: { locale },
});
const messages = data.intl.reduce((msgs, msg) => {
msgs[msg.id] = msg.message; // eslint-disable-line no-param-reassign
return msgs;
}, {});
dispatch({
type: SET_LOCALE_SUCCESS,
payload: {
locale,
messages,
},
});
// remember locale for every new request
if (process.env.BROWSER) {
const maxAge = 3650 * 24 * 3600; // 10 years in seconds
document.cookie = `lang=${locale};path=/;max-age=${maxAge}`;
history.push(`?lang=${locale}`);
}
// return bound intl instance at the end
return getIntlFromState(getState());
} catch (error) {
dispatch({
type: SET_LOCALE_ERROR,
payload: {
locale,
error,
},
});
return null;
}
};
}