Marshall
Marshall

Reputation: 23

How to refetch api data on client side in next.js?

I need to reload the data from api once state changed. Is is possible to fetch data again with getInitialProps on client side?

Upvotes: 1

Views: 878

Answers (1)

Andres Jimenez
Andres Jimenez

Reputation: 96

Why don't you fetch the data on the componentDidMount?

componentDidMount() {
  yourAPI.fetch().then((pFetchData) => {
    this.setState({data: pFetchData});
  });
}

In practice, componentDidMount is the best place to put calls to fetch data, for two reasons:

  1. Using DidMount makes it clear that data won't be loaded until after the initial render. This reminds you to set up initial state properly, so you don't end up with undefined state that causes errors.
  2. If you ever need to render your app on the server (SSR/isomorphic/other buzzwords), componentWillMount will actually be called twice “ once on the server, and again on the client “ which is probably not what you want. Putting the data loading code in componentDidMount will ensure that data is only fetched from the client.

https://www.codeproject.com/Articles/1177776/Where-to-Fetch-Data-componentWillMount-vs-componen

Hope it helps :)

Upvotes: 2

Related Questions