Skip to content

Commit 027334f

Browse files
thchiaRyan Johnson
authored andcommitted
Allow passing of custom getState function (e..g for immutable redux stores). (#112)
1 parent 66e5ee2 commit 027334f

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

src/LocalizeProvider.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ type LocalizeProviderState = {
2222

2323
export type LocalizeProviderProps = {
2424
store?: Store<any, any>,
25+
getState?: Function,
2526
children: any
2627
};
2728

@@ -68,9 +69,10 @@ export class LocalizeProvider extends Component<
6869
if (!this.props.store) {
6970
return;
7071
}
72+
const getState = this.props.getState || (state => state.localize);
7173

72-
const prevLocalizeState = prevState && prevState.localize;
73-
const curLocalizeState = this.props.store.getState().localize;
74+
const prevLocalizeState = prevState && getState(prevState);
75+
const curLocalizeState = getState(this.props.store.getState());
7476

7577
const prevActiveLanguage =
7678
prevState && getActiveLanguage(prevLocalizeState);

src/index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ export interface LocalizeContextProps {
8282

8383
export interface LocalizeProviderProps {
8484
store?: Store<any>;
85+
getState?: (state: any) => LocalizeState;
8586
children: any;
8687
}
8788

tests/LocalizeProvider.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import React from 'react';
22
import Enzyme, { shallow, mount } from 'enzyme';
33
import { createStore, combineReducers } from 'redux';
44
import Adapter from 'enzyme-adapter-react-16';
5+
import { Map } from 'immutable'
56
import { LocalizeProvider } from '../src/LocalizeProvider';
67
import { localizeReducer } from '../src/localize';
78
import { getTranslate, getLanguages, initialize } from '../src';
@@ -30,6 +31,10 @@ describe('<LocalizeProvider />', () => {
3031
localize: localizeReducer
3132
}));
3233
};
34+
const getImmutableStore = () => {
35+
const reducer = (s, a) => Map({localize: localizeReducer(s, a)});
36+
return createStore(reducer, Map({localize: initialState}));
37+
}
3338

3439
it('should set default values for localize state', () => {
3540
const wrapper = shallow(
@@ -70,4 +75,15 @@ describe('<LocalizeProvider />', () => {
7075
)
7176
}).not.toThrow();
7277
});
78+
79+
it('should allow passing a custom function to access state', () => {
80+
const store = getImmutableStore();
81+
expect(() => {
82+
shallow(
83+
<LocalizeProvider store={store} getState={state => state.get('localize')}>
84+
<div>Hello</div>
85+
</LocalizeProvider>
86+
)
87+
}).not.toThrow();
88+
});
7389
});

0 commit comments

Comments
 (0)