After diving into Next.js, I found the learning curve to be manageable since React was already familiar territory for me.
Currently, my focus is on implementing dynamic routing in my application -
Starting with my live/index.js file - (Where I utilize getServerSideProps to fetch initial data from an external API)
import Link from "next/link";
export async function getServerSideProps() {
// Retrieve data from external API
const res = await fetch(`https://api.pandascore.co/matches/running?sort=&page=1&per_page=50&token=#`)
const data = await res.json()
const games = data;
// Pass data to the page through props
return {
props:
{
results: games,
}
}
}
const liveGames = ({ results }) => {
return (
<div>
<div className="game-container">
<h2>Live Games NOW - </h2>
{results.map((q) => (
<Link href = {'/live/' + q.slug}key={q.slug}>
<a className="live_link"> <h3>{q.name}</h3></a>
</Link>
))}
</div>
</div>
)
}
export default liveGames;
Next up, my live/[slug].js file - (Here I display more details about each game upon click)
export const getStaticPaths = async () => {
const res = await fetch(`https://api.pandascore.co/matches/running?sort=&page=1&per_page=50&token=#`);
const data = await res.json();
const paths = data.map(o => {
return {
params: { slug: o.slug.toString() }
}
})
return {
paths,
fallback: false
}
}
export const getStaticProps = async (context) => {
const slug = context.params.slug;
const res = await fetch(`https://api.pandascore.co/matches/running?search[slug]=${slug}&token=#`);
const data = await res.json();
console.log(data)
return {
props: {
game: data
}
}
}
const live = ({ game }) => {
return (
<div>
<p></p>
<h1>{game.name}</h1>
<h1>{game.id}</h1>
</div>
);
}
export default live;
Overall, everything seems to be functioning as intended. My index page is properly routed and the URLs are generated based on the slug. I'm even receiving data in my console from [slug].js
. However, the return() statement isn't rendering any content at all, and I'm struggling to identify the root cause without any error messages or clues.
I also have a query regarding the use of getServerSideProps in index.js
and getStaticPaths in [slug].js
. Will this potentially lead to CORS issues in production or is it considered acceptable practice? (Given my limited experience with Next.js, I was advised by my API provider to handle all API requests on the server side using Next.js).