Skip to content

Instantly share code, notes, and snippets.

@tiagobbraga
Forked from dstreet/next-hoc.js
Created June 12, 2021 15:34
Show Gist options
  • Save tiagobbraga/bef9d0dc7a987ea75fbc3a8b8cdf4f4d to your computer and use it in GitHub Desktop.
Save tiagobbraga/bef9d0dc7a987ea75fbc3a8b8cdf4f4d to your computer and use it in GitHub Desktop.
Example HOC with Next.js
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment