Asked By: Anonymous
In _app.js
, I wrapped my MyApp
with a HOC (Higer Order Component) that fetches the status of an user.
import AuthHoC from '../utils';
import App from 'next/app';
class MyApp extends App {
render() {
const { Component, pageProps, isAuthenticated, idToken } = this.props;
return (
<Component
{...pageProps}
isAuth={isAuthenticated} // Given by AuthHOC
idToken={idToken} // Given by AuthHOC
/>
);
}
}
export default AuthHoC(MyApp);
In my page, I’d like to fetch the status through getInitialProps
.
class Page extends React.Component {
...
render() {
return (
<Layout>...</Layout>
);
}
}
Page.getInitialProps = async (ctx) => {
console.log('How can I access this -> isAuthenticated');
// if user is not auth, redirect or pass.
return {}
};
export default Page;
How can I fetch isAuthenticated
in Page.getInitialProps
?
Of course I can use ComponentDidMount()
to redirect based on the users’ status, but there’s a slight loading time, where they can see the page before Router.push('/')
triggers. That’s why I thought it’d be more appropriate to use getInitialProps
instead.
Solution
Answered By: Anonymous
It’s not possible to access instance properties from a static method.
See: How to access non static property from static function in typescript
Despite it being typescript, the same rules apply.