Last active
October 1, 2017 23:16
-
-
Save bradennapier/59192f736bf1c4d77a4cda8a7532facf to your computer and use it in GitHub Desktop.
Example to show implementation of hoist methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import hoistMethods from 'hoist-non-react-methods'; | |
const METHODS = { | |
set(timeoutID, fn, delay) { | |
METHODS.delete.call(this, timeoutID); | |
const cancelToken = setTimeout(() => { | |
METHODS.delete.call(this, timeoutID); | |
fn(); | |
}, delay); | |
this._map.set(timeoutID, cancelToken); | |
return this; | |
}, | |
clear() { | |
for (const [timeoutID, cancelToken] of this._map) { | |
clearTimeout(cancelToken); | |
this._map.delete(timeoutID); | |
} | |
}, | |
has(timeoutID) { | |
return this._map.has(timeoutID); | |
}, | |
delete(timeoutID) { | |
if (this._map.has(timeoutID)) { | |
const cancelToken = this._map.get(timeoutID); | |
clearTimeout(cancelToken); | |
this._map.delete(timeoutID); | |
} | |
}, | |
}; | |
export default function ConnectTimeoutWrapper(WrappedComponent) { | |
class ConnectedTimeoutMap extends React.Component { | |
componentWillMount() { | |
this._map = new Map(); | |
} | |
componentDidMount() { | |
hoistMethods('_wrapped', this); | |
} | |
componentWillUnmount() { | |
METHODS.clear.call(this); | |
} | |
_addTimeoutProps = props => ({ | |
...props, | |
timeout: { | |
set: (...args) => METHODS.set.call(this, ...args), | |
clear: (...args) => METHODS.clear.call(this, ...args), | |
has: (...args) => METHODS.has.call(this, ...args), | |
delete: (...args) => METHODS.delete.call(this, ...args), | |
}, | |
ref: ref => { | |
this._wrapped = ref; | |
}, | |
}); | |
render = () => React.createElement(WrappedComponent, this._addTimeoutProps(this.props)); | |
} | |
ConnectedTimeoutMap.WrappedComponent = WrappedComponent; | |
ConnectedTimeoutMap.displayName = `WithTimeoutMap(${WrappedComponent.displayName || | |
WrappedComponent.name || | |
'Component'})`; | |
return ConnectedTimeoutMap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment