Caden
Caden

Reputation: 41

Can I move getInitialProps code to componentDidMount?

I want to move the code in static getInitialProps to componentDidMount. However, there are two parameters(component, ctx) in getInitialProps and I should use them all. I just want to know whether I can move the code. Thank you!

No Idea..

// Current
class extends App {
  public static async getInitialProps({Component, ctx}) {
     // Do Something with two parameters
  }
  .
  .
  .
}

// What I want to do
class extends App {
  public componentDidMount() {
    // Do the same thing
  }
  .
  .
  .
}

Upvotes: 1

Views: 1855

Answers (1)

Pavindu
Pavindu

Reputation: 3112

getInitialProps works in both server and client side while componentDidMount is only for the client side.Therefore, you can't use it inside componentDidMount.

If you want to use data fetched in getInitialProps inside componentDidMount, you can return data from getInitialProps and use it as a prop.

class extends App{
  static async getInitialProps({ Component, ctx }) {
    //do some data fetching
    return { data };
  }

  constructor() {
    super();
    this.state = {};
  }

  componentDidMount() {
    console.log(this.props.data)
  } 

}

Upvotes: 1

Related Questions