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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With