In NextJS, how do i add getInitialProps() to a HOC-wrapped-functional-element?

1.2k Views Asked by At

I have a HOC-wrapped-functional-component here

export default wrapperHoc( function myComponent ({ someProps }){
    return(
       <div/>
    )
})

How do i write getInitialProps for myComponent ?

Should i call myComponent's getInitialProps in wrapperHoc?

2

There are 2 best solutions below

0
windmaomao On BEST ANSWER
  const YourNewComponent = wrapperHoc(...)

  YourNewComponent.getInitialProps = async (ctx) => {
    const res = await fetch('https://api.github.com/repos/vercel/next.js')
    const json = await res.json()
    return { stars: json.stargazers_count }
  }

  export default YourNewComponent
0
Iceberg On

Should i call myComponent's getInitialProps in wrapperHoc?

Yes, you're on the right track.

The next.js documentation says that `getInitialProps can not be used in children components, only in the default export of every page.

To work around this limitation, you write getInitialProps in myComponent, then call myComponent's getInitialProps in wrapperHoc. And wrapperHoc's getInitialProps should also be called by upper component this way.

wrapperHoc.js example

You're free to tweak the getInitialProps() to add additional properties and to tweak render() to add additional html elements.

export default (WrappedComponent) => (class WrapperHOC extends React.Component {
    static async getInitialProps(args) {
        return WrappedComponent.getInitialProps ? await WrappedComponent.getInitialProps(args) : {};
    }
    render() {
        return (
          <WrappedComponent {...this.props} />
        );
    }

});