This repository has been archived by the owner on Jan 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
dynamic.js
69 lines (55 loc) · 2.37 KB
/
dynamic.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
/**
* Copyright 2018, IOOF Holdings Limited.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { useContext, useEffect, useState } from 'react'
import { ReactReduxContext } from 'react-redux'
import hoistNonReactStatics from 'hoist-non-react-statics'
import wrapDisplayName from 'recompose/wrapDisplayName'
import { createDynamicTarget } from '@redux-dynostore/core'
import isObject from './utils/isObject'
const splitOptions = args => {
const [lastItem] = args.slice(-1)
return isObject(lastItem) ? [args.slice(0, -1), lastItem] : [args, {}]
}
const DynamicContext = React.createContext(null)
// eslint-disable-next-line react/prop-types
export const DynamicProvider = ({ children }) => {
const inheritedFirstRender = useContext(DynamicContext)
const [firstRender, setFirstRender] = useState(inheritedFirstRender === null)
useEffect(() => {
setFirstRender(false)
}, [])
return <DynamicContext.Provider value={firstRender}>{children}</DynamicContext.Provider>
}
const createDynamic = (identifier, enhancers, options) => {
const { context = ReactReduxContext } = options
const dynamicEnhancer = createDynamicTarget(enhancers)(identifier)
return Component => {
const Dynamic = React.forwardRef((props, ref) => {
const { store } = useContext(context)
const [lastStore, setLastStore] = useState(store)
const firstRender = useContext(DynamicContext)
const [EnhancedComponent, setEnhancedComponent] = useState(() => firstRender && dynamicEnhancer(store)(Component));
useEffect(() => {
if (!EnhancedComponent || store !== lastStore) {
setEnhancedComponent(() => dynamicEnhancer(store)(Component));
setLastStore(store)
}
}, [store])
return EnhancedComponent && <EnhancedComponent identifier={identifier} {...props} ref={ref} />
})
hoistNonReactStatics(Dynamic, Component)
Dynamic.displayName = wrapDisplayName(Component, 'Dynamic')
Dynamic.createInstance = (instanceIdentifier, ...instanceEnhancers) =>
createDynamic(instanceIdentifier, enhancers.concat(instanceEnhancers), options)(Component)
return Dynamic
}
}
const dynamic = (identifier, ...enhancers) => {
return createDynamic(identifier, ...splitOptions(enhancers))
}
export default dynamic