Skip to content

Instantly share code, notes, and snippets.

@marsch
Created February 6, 2017 13:27
Show Gist options
  • Save marsch/697532db3f45e2af0d365e0b7dccdae3 to your computer and use it in GitHub Desktop.
Save marsch/697532db3f45e2af0d365e0b7dccdae3 to your computer and use it in GitHub Desktop.
import { h, Component } from 'preact'
import { PropTypes } from 'preact-compat'
import { withRouter } from 'react-router'
import { connect } from 'react-redux'
// OPTIONAL: patch Component by default (you might want to delete this if you're a purist)
Component.prototype.linkRef = function(name) {
return linkRef(this, name)
}
export function linkRef(component, name) {
const cache = component._linkedRefs || (component._linkedRefs = {})
if (!component.refs) component.refs = {}
return cache[name] || (cache[name] = c => {
component.refs[name] = c
})
}
export default function ensure(fn, mapStateToProps, mapDispatchToProps) {
return (DecoratedComponent) => {
DecoratedComponent = connect(mapStateToProps, mapDispatchToProps)(DecoratedComponent)
@withRouter
class EnsureDataDecorator extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
}
componentDidMount =() => {
const { decorated } = this.refs
const { store, router } = this.context
decorated.setState({ loadstate: 'loading' })
Promise.all([fn({ store, params: router.params, location: router.location })])
.then(() => decorated.setState({ loadstate: 'loaded' }))
.catch((e) => {
decorated.setState({ loadstate: 'failed', loaderror: e })
})
}
render() {
return (
<DecoratedComponent ref={::this.linkRef('decorated')} {...this.props} />
)
}
}
return EnsureDataDecorator
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment