Search code examples
javascriptfetchnext.jsrest

Why do I get a "cannot read property of undefined" error when the data is defined?


export async function getPrices() {
  const res = await fetch(
    "https://sandbox.iexapis.com/stable/crypto/BTCUSD/price?token=Tpk_1d3fd3aee0b64736880534d05a084290"
  );
  const quote = await res.json();

  return {
    props: { quote }
  };
}

export default function IndexPage({ quote }) {
  return (
    <div>
      <p>{quote.price}</p>
    </div>
  );
}

I'm trying to return the price of a cryptocurrency using an API called IEX Cloud, which seems to work fine when tested in Postman. My problem is I can't seem to return the data on my Next.js app.

Please find the MRE here:

Edit nostalgic-wave-6sidm

I get TypeError: Cannot read property 'price' of undefined, but if you access the route in a browser or Postman you can see there is a 'price' defined.

https://sandbox.iexapis.com/stable/crypto/BTCUSD/price?token=Tpk_1d3fd3aee0b64736880534d05a084290

<p>{quote.price}</p> is the line in my code that throws up the error.

I'm sure it's a very obvious misunderstanding on my part but I am really stuck. Can anyone help?


Solution

  • You need to change the function name getPrices to getServerSideProps

    Here is your refactor code in codesandbox.

    https://codesandbox.io/s/billowing-frost-lb9xm?file=/pages/index.js

    or you can create separate function for getPrices and call it in getServerSideProps