简体   繁体   中英

How do I pass a prop from from component to getServerSideProps() in NextJS?

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,
    }
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM