-
-
Save dstreet/7642b229e33f3cfe137dd7f3bae7a37d to your computer and use it in GitHub Desktop.
import React from 'react' | |
/* | |
* Higher order component that passes `getInitialProps` through | |
* to the child component | |
*/ | |
const HOC = function(Child) { | |
return class Higher extends React.Component { | |
static getInitialProps(ctx) { | |
return Child.getInitialProps(ctx) | |
} | |
} | |
} | |
/* | |
* Child component | |
*/ | |
const class MyComponent extends React.Component { | |
static getIntialProps({ req }) { | |
// Do something asynchronously... | |
// Not strickly necessary. Just an example | |
const promise = new Promise((resolve, reject) => { | |
setTimeout(() => res(), 500) | |
}) | |
return promise.then(() => ({ initialState: { foo: 'bar' }, isServer })) | |
} | |
render() { | |
return <h1>Hello, World</h1> | |
} | |
} | |
export default HOC(MyComponent) |
There is something missing in above code. It doesn't work in most of the cases. You forget to getInitialProps
The correct one is:
const PageWrapper = (Page) => {
return class extends React.Component {
static getInitialProps(ctx) {
if(Page.getInitialProps)
return Page.getInitialProps(ctx);
}
render() {
return <Page {...this.props}/>
}
}
}
Thanks bro ! It fixes my bug !!!
I dont understand why your getInitialProps
would fire off when it's inside a HOC (so not in "/pages" presumably). It's in a HOC and inside the inner class that's returned.
I get that you could pass in your component and then programatically fire off that Page.getInitialProps - but then putting that logic inside the HOC's getInitialProps
means it's never fired off, no?
What am i missing here?
I do no understand why getInitialProps
works inside a HOC either. It would be good if someone could shed some light on this
This was a quick example of an initial props pass through. It was made for a really old version of Next.js. Mileage may vary with newer versions
for example a private route for your app
const PrivateRoute = (AuthComponent) => {
return class Higher extends React.Component {
static async getInitialProps(ctx) {
const pageProps =
AuthComponent.getInitialProps &&
(await AuthComponent.getInitialProps(ctx))
// Return props.
return { ...pageProps }
}
render() {
return <AuthComponent {...this.props} />;
}
};
};
export default PrivateRoute;
Await is implicit when you have an async function. So the parent component's getInitialProps method can return the result of an async function without await.