0

I'm trying to move some API fetch code out of a main page in my Next.js app and into a component file. Mostly in order to keep things organised and reduce the amount of code in the main page.

On the main page the API fetching is done inside getInitialProps as it uses async functions. This all works fine. I've now moved the code into a component file but the props aren't returning anything to the main page.

Component file:

// Link removed for security.
const sheet = 'GOOGLE_SHEETS_API_LINK';

// Function to fetch cell data from a Google Sheet.
async function getCellData(url,array1,array2) {
  let doTheFetch = await fetch(url);
  let jsonify = await doTheFetch.json();
  let getValue = jsonify.values[array1][array2];
  return getValue;
}

export async function getServerSideProps() {
  const testDataReturn = () => {
    // Sheet API link & position of data in the nested array that's returned.
    return getCellData(sheet,0,0)
  }
  const testDataReturnOutput = await testDataReturn();

  return {
    props: {
        message: 'Hello world!',
        testDataReturnOutput: testDataReturnOutput
    }
  }
}

function Page({ message, testDataReturnOutput }) {
  return (
      <>
          <h1>Example page</h1>
          <h2>{message}</h2>
          <div>Cell data: {testDataReturnOutput}</div>
      </>
  )
}

export default Page

Relevant code on my main index page:

import Page from '../components/Page';

function Dashboard(props) {
  return (
    <Page />
  );
}

export default Dashboard

I can import this component file normally in the main page. The issue is that the HTML is rendered but the props: {message} and {testDataReturnOutput} are not. Do I need to pass down the props in a different way?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Sam R
  • 71
  • 1
  • 6
  • Does this answer your question? [Next.js, getStaticProps not working with component but does with page](https://stackoverflow.com/questions/71310271/next-js-getstaticprops-not-working-with-component-but-does-with-page) – Youssouf Oumar Jan 11 '23 at 10:15

0 Answers0