Skip to content

Instantly share code, notes, and snippets.

@timbielawski
Created December 31, 2018 13:13
Show Gist options
  • Save timbielawski/6cb793ea8cf8aa22ba32ef88687c42c1 to your computer and use it in GitHub Desktop.
Save timbielawski/6cb793ea8cf8aa22ba32ef88687c42c1 to your computer and use it in GitHub Desktop.
HOC for nextJs App for separating getInitialProps from page component
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