0

I want to pass a props from my component to getServerSideProps(). They are both on the same page. I the code below I want pass url from my component to getServerSideProps() so that I can use the same url to get the data from API.

export default function Home({data}) {
  
  const [number, getNumber] = useState("9999999999")
  const url =`{http://apilayer.net/api/validate?access_key=e52d69f119348057d68ec090d2d10978&number=${number}}`;

  return (
    <div>
      <Head>
        <title>Numverify</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main>
        <div className="h-16 dark:bg-gray-900 bg-white shadow-md flex justify-center items-center">
          <span className="text-gradient font-bold text-xl">NumVerify</span>
        </div>
      </main>
    </div>
  )
}

export async function getServerSideProps() {
  const res = await fetch(url);
  const data = await res.json();

  return {
    props: {
      data,
    }
  }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • You can't pass data to `getServerSideProps` from your component, the data flows the other way around, from `getServerSideProps` to your React component. – juliomalves Jul 30 '21 at 13:55
  • So what should I use in place of getServerSideProps? – Srijan Saha Jul 30 '21 at 14:32
  • Does this answer your question? [How to recall getServerSideProps from same component with updated api url?](https://stackoverflow.com/questions/66299462/how-to-recall-getserversideprops-from-same-component-with-updated-api-url) – juliomalves Aug 01 '21 at 11:08

1 Answers1

0

You appear to have misunderstood what getServerSideProps does.

The docs state:

If you export an async function called getServerSideProps from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.

So the data that you return will be passed to your Home component, not the other way round.

tarmes
  • 15,366
  • 10
  • 53
  • 87