Arthur
Arthur

Reputation: 3516

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.

Upvotes: 4

Views: 4800

Answers (2)

Yilmaz
Yilmaz

Reputation: 49739

use axios or isomorphic-unfetch. they work both in client and server environments. Fetch API does not exist in the Node.js environment. it. If you still want to use Fetch API in your client-side code, you should use a isomorphic-unfetch. When you are in the browser, it uses the unfetch polyfill. If your code runs in Node.js, it switches to node-fetch.

import "axios" from "axios"

static async getInitialProps(){
    const res=await axios.get('url')//
    const data=res.data
    return {data}
}

UPDATE

In addition to fetch() on the client-side, Next.js polyfills fetch() in the Node.js environment. You can use fetch() in your server code (such as getStaticProps/getServerSideProps) without using polyfills such as isomorphic-unfetch or node-fetch.

https://nextjs.org/docs/basic-features/supported-browsers-features

Upvotes: 2

Melchia
Melchia

Reputation: 24324

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;

Upvotes: 1

Related Questions