I have implemented the following code in my pages/github file, and when I navigate to localhost:3000/github, the code runs successfully and returns JSON data.
function GithubAPI(props) {
// Display posts...
return (<div>{props.data.name}</div>)
}
// This function is invoked during build time
export async function getStaticProps() {
// Fetch data from an external API endpoint
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
However, when I try to import this component into another one, I encounter some issues.
In my pages/about file
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 am unsure of how Next.js developers expect us to organize our code in order to make API calls like these and still be able to export components for importing into other parts of the application. How should I structure my code to achieve this?