Created
August 30, 2017 21:25
-
-
Save hubgit/1e2e53d0735f9ae6e663bc394fccc4b9 to your computer and use it in GitHub Desktop.
ConnectPage HOC for async actions that must be completed before rendering
This file contains hidden or 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 React from 'react' | |
import { compose } from 'recompose' | |
import { connect } from 'react-redux' | |
import { withRouter } from 'react-router' | |
import classes from './ConnectPage.local.css' | |
const ConnectPage = requirements => WrappedComponent => { | |
class ConnectedComponent extends React.Component { | |
state = { | |
fetching: false, | |
complete: false, | |
error: null | |
} | |
componentDidMount () { | |
this.fetch(this.props) | |
} | |
componentWillReceiveProps (nextProps) { | |
this.fetch(nextProps) | |
} | |
fetch ({ isAuthenticated }) { | |
if (!isAuthenticated) { | |
return | |
} | |
if (this.state.fetching) { | |
return | |
} | |
this.setState({ | |
fetching: true, | |
complete: false | |
}) | |
const requests = requirements(this.props.params).map(this.props.dispatch) | |
Promise.all(requests).then(() => { | |
this.setState({ | |
fetching: false, | |
complete: true, | |
}) | |
}).catch(error => { | |
this.setState({ | |
error: error.message | |
}) | |
console.error(error) | |
throw error // rethrow | |
}) | |
} | |
render () { | |
const { complete, error } = this.state | |
if (error) return ( | |
<div className={classes.error}>{error}</div> | |
) | |
if (!complete) return ( | |
<div className={classes.bar}>loading…</div> | |
) | |
return <WrappedComponent {...this.props}/> | |
} | |
} | |
return compose( | |
connect( | |
state => ({ | |
isAuthenticated: state.currentUser.isAuthenticated | |
}) | |
), | |
withRouter | |
)(ConnectedComponent) | |
} | |
export default ConnectPage |
This file contains hidden or 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 React from 'react' | |
import classes from './ConnectPage.local.css' | |
const ConnectPage = WrappedComponent => { | |
return ({ data: { loading, error, ...model }, ...rest }) => { | |
if (error) return ( | |
<div className={classes.error}>{error}</div> | |
) | |
if (loading) return ( | |
<div className={classes.bar}>loading…</div> | |
) | |
return <WrappedComponent {...model} {...rest}/> | |
} | |
} | |
export default ConnectPage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment