Reputation: 19
I'm trying to learn Next.JS and after learning about getStaticPaths()
I wanted to use it in a 'real life example'. However, contrary to the examples made with JSONPlaceholder it seems that I can't get it to work, and instead I get a 404 error with no messages whatsoever. So I wanted to ask what am I doing wrong:
index.js
import Link from 'next/dist/client/link';
const CHAMPIONS_URL =
'https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champion-summary.json';
export async function getStaticProps() {
const res = await fetch(CHAMPIONS_URL);
const champions = await res.json();
return {
props: { champions },
};
}
const Champions = ({ champions }) => {
// console.log(champions);
return (
<ul>
{champions.slice(1).map((champion) => (
<li key={champion.id}>
<Link href={`/champions/${champion.name}`}>{champion.name}</Link>
</li>
))}
</ul>
);
};
export default Champions;
[id].js
const CHAMPIONS_URL =
'https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champion-summary.json';
function getChampion(champion) {
return `https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champions/${champion}.json`;
}
export async function getStaticPaths() {
const res = await fetch(CHAMPIONS_URL);
const champions = await res.json();
const paths = champions.map((champion) => ({ params: { id: champion.id.toString() } }));
return { paths, fallback: false };
}
export async function getStaticProps({ params }) {
const res = await fetch(getChampion(params.id));
const champion = await res.json();
return { props: { champion } };
}
const Champion = ({ champion }) => {
console.log(champion);
return <div>Champion</div>;
};
export default Champion;
Upvotes: 0
Views: 505
Reputation: 2196
Your approach is fine. The 404 error you're seeing doesn't originate from Next.js itself, but from the external endpoint inside your getChampion()
function in ./pages/champions/[id].js
(and make sure [id].js
exists in a directory named champions
).
Passing champion.name
to ${champion}.json
will result in an error after interpolation since you're expecting to use params.id
:
https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champions/Annie.json
But passing champion.id
instead will work:
https://raw.communitydragon.org/latest/plugins/rcp-be-lol-game-data/global/default/v1/champions/1.json
So you really just need to change your <Link>
component in .pages/index.js
from...
{/* if you use `name` this will error */}
<Link href={`/champions/${champion.name}`}>{champion.name}</Link>
...to:
{/* but if you use `id` (since your page is named `[id].js`) this should work */}
<Link href={`/champions/${champion.id}`}>{champion.name}</Link>
Upvotes: 1