Created
December 31, 2018 13:13
-
-
Save timbielawski/6cb793ea8cf8aa22ba32ef88687c42c1 to your computer and use it in GitHub Desktop.
HOC for nextJs App for separating getInitialProps from page component
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 ErrorPage from 'next/error'; | |
import errorCodeMapper from '../server/error-code-mapper'; | |
const withInitProps = getInitPropsFunc => WrappedComponent => { | |
return class InitProps extends React.Component { | |
static async getInitialProps(args) { | |
try { | |
return await getInitPropsFunc(args); | |
} catch (error) { | |
return { error }; | |
} | |
} | |
render() { | |
if (this.props.error) { | |
return <ErrorPage statusCode={errorCodeMapper(this.props.error)} /> | |
} | |
return ( | |
<div className="next-page-wrapper"> | |
<WrappedComponent {...this.props} /> | |
</div> | |
); | |
} | |
}; | |
}; | |
export default withInitProps | |
//Usage where getIndexInitialProps is the function to be run in `static async getInitialProps` | |
export default compose( | |
setDisplayName("IndexPage"), | |
withRedux(initStore, mapStateToProps, mapDispatchToProps), | |
withInitProps(getIndexInitialProps) | |
)(Main); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment