-
Notifications
You must be signed in to change notification settings - Fork 4
/
GlobalStoreProvider.tsx
52 lines (41 loc) · 1.43 KB
/
GlobalStoreProvider.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
import React, { Context, createContext, useContext } from 'react';
import GlobalStore from '../../../stores/GlobalStore';
import environment from 'environment';
/**
* A reference to a "single" instance of the global store.
*/
let _globalStore: GlobalStore;
/**
* getGlobalStore should be used outside of React component lifecycle.
*/
export const getGlobalStore = (): GlobalStore => _globalStore;
/**
* setupGlobalStore sets up the initial global store.
*/
export const setupGlobalStore = (initialState: Partial<GlobalStore> = {}): GlobalStore => {
// Always create a new store for SSG and SSR
if (!_globalStore || environment.isServer) {
_globalStore = new GlobalStore();
}
if (initialState) {
_globalStore.hydrate(initialState);
}
return _globalStore;
};
export const GlobalStoreContext: Context<GlobalStore> = createContext(setupGlobalStore());
/**
* useGlobalStore should be used in React Components.
*/
export const useGlobalStore = (): GlobalStore => useContext(GlobalStoreContext);
/**
* Global Store Provider Component
*/
interface IProps {
hydrationData?: Partial<GlobalStore>;
}
export const GlobalStoreProvider: React.FC<IProps> = (props) => {
_globalStore = setupGlobalStore(props.hydrationData);
return <GlobalStoreContext.Provider value={_globalStore}>{props.children}</GlobalStoreContext.Provider>;
};
GlobalStoreProvider.displayName = 'GlobalStoreProvider';
GlobalStoreProvider.defaultProps = {};