William
William

Reputation: 4578

How to make a basic external data fetch using Next.js and import component into another

I have the code below in pages/github and when I go to localhost:3000/github the code executes as expected. I get JSON data.

function GithubAPI(props) {
  // Render posts...
  return (<div>{props.data.name}</div>)
}

// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://api.github.com/repos/vercel/next.js')

  const data= await res.json()
  console.log(data)

  return {
    props: {
      data,
    },
  }
}

export default GithubAPI

When I import this component into another component I get problems.

pages/about

import GithubAPI from './github'
function About(props) {
    console.log(props)

  return (
    <div>
      <div>About</div>
       <GithubAPI/>  {/* TypeError: Cannot read property 'name' of undefined */}

    </div>
  )
}

export default About

I do not know how the developers of Next.js expect us to structure our code so that we can make these kinds of API calls and still export our components for import into other components. How am I expected to do this?

Upvotes: 0

Views: 357

Answers (1)

NicholasG04
NicholasG04

Reputation: 361

You cannot run getStaticProps/getServerSideProps in any non-page components. One must prop pass instead.

Upvotes: 1

Related Questions