Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getInitialProps with HOC which also contains getInitialProps

I wrapped a page with a withAuth HOC. in the same page, i also tried to call getInitialProps. if i sign in, the getInitialProps function doesn't run (though it shows that my withAuth HOC is working).

is there anyway i can make getInitialProps for the Contact Page to work and also use the withAuth HOC (which also has a getInitialProps function)?

Contact

import Layout from "../components/Layout";
import { withAuth } from "../services/withAuth";

class Contact extends React.Component {
  static async getInitialProps(ctx) {
    console.log("@contact authenticated ", ctx);
    return {};
  }
  render() {
    return (
      <Layout>
        <p>hey there</p>
        <a href="mailto:[email protected]">[email protected]</a>
      </Layout>
    );
  }
}

export default withAuth(Contact);

withAuth HOC

import { ME } from "../graphql/queries";
import redirect from "../lib/redirect";

export const withAuth = C => {
  class AuthComponent extends React.Component {
    static async getInitialProps(ctx) {
      const response = await ctx.apolloClient.query({ query: ME });
      console.log("@withAuth ", response);
      if (!response || !response.data || !response.data.me) {
        redirect(ctx, "/");
        return {
          me: null
        };
      }

      return {
        me: response.data.me
      };
    }

    render() {
      return <C {...this.props} />;
    }
  }

  return AuthComponent;
};
like image 624
Hendry Lim Avatar asked Apr 26 '19 14:04

Hendry Lim


1 Answers

Try calling C.getInitialProps() inside the getInitialProps of your HOC:

export const withAuth = C => {
  class AuthComponent extends React.Component {
    static async getInitialProps(ctx) {
      const response = await ctx.apolloClient.query({ query: ME });

      console.log("@withAuth ", response);

      if (!response || !response.data || !response.data.me) {
        redirect(ctx, "/");
        return {
          me: null
        };
      }

      // Get component’s props
      let componentProps = {}
      if (C.getInitialProps) {
        componentProps = await C.getInitialProps(ctx);
      }

      return {
        me: response.data.me,
        ...componentProps
      };
    }

    render() {
      return <C {...this.props} />;
    }
  }

  return AuthComponent;
};

I hope this helps.

like image 132
Steve Holgado Avatar answered Nov 04 '22 05:11

Steve Holgado