0

I face an issue with Next.JS and fetching initial props to my pages. I am doing an application with several (7-8) pages. One the left menu, once a an icon is clicked, the router is pushing the user to the proper page. Then if the user is logged in, the page and child components load. Everything works, as I am trying to cover loading time with a loading component, something like this:

  render() {

if (this.props.data !== undefined) {
  return (<Provider store={store}><Main info={this.props.data}  path={this.props.url.pathname} user={this.props.user} token={this.props.token} /></Provider>)
} else {
  return (<Loading />)
}}

The designed goal is to kick the Loading Component when the data is fetching. Not after. I was trying to do it with React lifecycle hooks, but it seems that `

static async getInitialProps({req})

Comes before everything. Have a look on the entire code

export default class Component extends React.Component {

static async getInitialProps({req}) {
const authProps = await getAuthProps(req, 
'url')
return authProps;
  }

  componentDidMount() {
if (this.props.data === undefined) {
  Router.push('/login')
}
  }

  render() {

if (this.props.data !== undefined) {
  return (<Provider store={store}><Main info={this.props.data}  path={this.props.url.pathname} user={this.props.user} token={this.props.token} /></Provider>)
} else {
  return (<Loading />)
}}}
Koppany
  • 57
  • 9

1 Answers1

0

getInitalProps is being called when the Page component is rendered. You should not use it in any other components since it won't work. That is not part of React Lifecycle but Next's implementation. I believe what you wanna do is just fetch data and measure its loading time. If so, then using a componentDidMount might be enough.

elmasse
  • 221
  • 2
  • 4