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?



Read more here: https://stackoverflow.com/questions/64947209/how-to-make-a-basic-external-data-fetch-using-next-js-and-import-component-into

Content Attribution

This content was originally published by William at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: