Fetching External API Data
In this lesson you'll learn how to use data from an external API in your NextJS web app. For our example, we'll be using data from GitHub.
We'll be using https://api.github.com/orgs/dabblelab/repos
Create a constant to hold the endpoint URL in
index.json line 3.const defaultEndpoint = 'https://api.github.com/orgs/dabblelab/repos';Create a function to return the serverSideProps
export async function getServerSideProps() {
const response = await fetch(defaultEndpoint);
const data = await response.json();
return {
props: {
data
}
}
}Pass data into the
Homefunction on line 15 ofindex.jsexport default function Home({ data }) {
console.log('data', data);
return (
//code omitted for brevity
)
}Then refresh the page and use the devTools in Chrome to view the data logged to the console like the following screenshot shows.
[screenshot goes here]
Within the
Homefunction inindex.jsUse the data in the pageconst { results = [] } = data;Use the results
<div className={styles.grid}>
{data.map(result => {
const { id, name, description, html_url } = result;
return (
<a href={html_url} className={styles.card}>
<h2>{name} →</h2>
<p>{description}</p>
</a>
)
})}
</div>