Skip to content

Instantly share code, notes, and snippets.

@goldhand
Last active May 25, 2016 22:14
Show Gist options
  • Save goldhand/c1306e068cdd13f733bde8381e2bcc11 to your computer and use it in GitHub Desktop.
Save goldhand/c1306e068cdd13f733bde8381e2bcc11 to your computer and use it in GitHub Desktop.
High order component for listening to window load event and updating a redux store
import React, {Component, PropTypes} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as windowActions from 'actions/windowMonitorActions';
/**
* connectWindow is a high order component that will update the windowMonitor
* store once the client window has loaded and connect decorated component's
* prop, windowLoaded, to that store's state
*
* @example
* @connectWindow
* class ConnectedComponent extends Component {
*
* static propTypes = {
* windowLoaded: PropTypes.bool.isRequired,
* }
* ...
* }
*
* @param {class} ComponentClass - Component to be decoreated
* @return {class} - the decorated component
*/
export default (function connectWindow() {
// keep track of how many of these exist
const refs = {
creation: 0,
};
return (ComponentClass) => {
@connect(
state => ({...state.windowMonitor}),
dispatch => ({actions: bindActionCreators(windowActions, dispatch)})
)
class WindowMonitor extends Component {
static propTypes = {
actions: PropTypes.object.isRequired,
windowLoaded: PropTypes.bool.isRequired,
}
componentDidMount() {
if (!refs.creation) {
addEventListener('load', this.props.actions.windowLoaded);
}
refs.creation++;
}
componentWillUnmount() {
refs.creation--;
if (!refs.creation) {
removeEventListener('load', this.props.actions.windowLoaded);
}
}
render = () => <ComponentClass {...this.props} />;
}
return WindowMonitor;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment