Skip to content

Commit 4306275

Browse files
author
Long Ho
committed
fix: create initial intl for Provider
This is primarily so that enzyme `shallow` works. Looks like right now it does not trigger `getDerivedStateFromProps` before initial render which results in `this.state.intl` being `undefined`.
1 parent e172cba commit 4306275

File tree

1 file changed

+24
-30
lines changed

1 file changed

+24
-30
lines changed

src/components/provider.tsx

Lines changed: 24 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ interface State {
3636
*/
3737
intl?: IntlShape;
3838
/**
39-
* list of memoized props we care about.
39+
* list of memoized config we care about.
4040
* This is important since creating intl is
4141
* very expensive
4242
*/
43-
prevProps: OptionalIntlConfig;
43+
prevConfig: OptionalIntlConfig;
4444
}
4545

4646
export type OptionalIntlConfig = Omit<
@@ -49,6 +49,21 @@ export type OptionalIntlConfig = Omit<
4949
> &
5050
Partial<typeof DEFAULT_INTL_CONFIG>;
5151

52+
function filterIntlConfig<P extends OptionalIntlConfig = OptionalIntlConfig>(
53+
config: P
54+
): OptionalIntlConfig {
55+
return {
56+
locale: config.locale,
57+
timeZone: config.timeZone,
58+
formats: config.formats,
59+
textComponent: config.textComponent,
60+
messages: config.messages,
61+
defaultLocale: config.defaultLocale,
62+
defaultFormats: config.defaultFormats,
63+
onError: config.onError,
64+
};
65+
}
66+
5267
export default class IntlProvider extends React.PureComponent<
5368
OptionalIntlConfig,
5469
State
@@ -58,40 +73,19 @@ export default class IntlProvider extends React.PureComponent<
5873
private cache: IntlCache = createIntlCache();
5974
state: State = {
6075
cache: this.cache,
61-
intl: undefined,
62-
prevProps: {
63-
locale: this.props.locale,
64-
},
76+
intl: createIntl(filterIntlConfig(this.props)),
77+
prevConfig: filterIntlConfig(this.props),
6578
};
6679

6780
static getDerivedStateFromProps(
6881
props: OptionalIntlConfig,
69-
{prevProps, cache}: State
82+
{prevConfig, cache}: State
7083
) {
71-
const {
72-
locale,
73-
timeZone,
74-
formats,
75-
textComponent,
76-
messages,
77-
defaultLocale,
78-
defaultFormats,
79-
onError,
80-
} = props;
81-
const filteredProps: OptionalIntlConfig = {
82-
locale,
83-
timeZone,
84-
formats,
85-
textComponent,
86-
messages,
87-
defaultLocale,
88-
defaultFormats,
89-
onError,
90-
};
91-
if (!shallowEquals(prevProps, filteredProps)) {
84+
const config = filterIntlConfig(props);
85+
if (!shallowEquals(prevConfig, config)) {
9286
return {
93-
intl: createIntl(filteredProps, cache),
94-
prevProps: filteredProps,
87+
intl: createIntl(config, cache),
88+
prevProps: config,
9589
};
9690
}
9791
return null;

0 commit comments

Comments
 (0)