Search code examples
javascripthtmlreactjsfetchnext.js

Nextjs Fetch data when reloading the page


In React we fetch data using useEffect when reloading the page:

useEffect(() => {
  let ignore = false
  const fetchingData = async () => {
    const res = await fetch(<your_path>)
    const data = await res.json()
    if (!ignore) setData(data)
  }; 
  fetchingData()
  return () => { ignore = true }
}, [])

But how can I do this in Next.js? Fetch doesn't fire in getInitialProps when the page reloads.


Solution

  • In Next.js you usually load data with HTTP requests in getInitialProps then you can use them as props:

    const App = props => (
      <Layout>
      {props.data}
        ...
      </Layout>
    );
    
    App.getInitialProps = async function() {
      const res = await fetch(<your_path>)
      const data = await res.json()
      return {
       data
      }
    };
    
    export default App;