I am trying to display film details from this API ‘swapi.dev/api/films’ in NextJS but I keep getting an error. It has something to do with the getStaticPath function. I am using this code: any help welcome.
This is the ‘films’ code that displays details of all the episodes, and this is working ok.
import fetch from 'isomorphic-unfetch';
import Link from 'next/link'
export const getStaticProps = async () => {
const res = await fetch('https://swapi.dev/api/films');
const data = await res.json();
return {
props: {films:data.results}
}
}
const Films = ({films}) => {
return (
<div >
{films.map(film =>(
<div className='card'>
<Link className={styles.a} href = {'/details/' + film.episode_id} key ={film.episode_id}>
<p>{`Episode: ${film.episode_id}`} - <strong>{film.title}</strong></p>
</Link>
</div>
))}
</div>
and this is the code to display details of a selected episode and it is in this code I am getting the error.
import fetch from 'isomorphic-unfetch';
export const getStaticPaths = async () => {
const res = await fetch('https://swapi.dev/api/films');
const data = await res.json();
const paths = data.results.map(film => {
return {
params: { id: film.episode_id.toString() },
};
});
return {
paths,
fallback: false,
};
};
export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch(`https://swapi.dev/api/films/${id}`);
const data = await res.json();
return {
props: { film: data },
};
};
const Details = ({ film }) => {
return (
<div>
<h1>Episode {film.episode_id}</h1>
<h1>{film.title}</h1>
</div>
);
};
export default Details;
I get the server error shown below.
I have also tried taking ‘results’ out of ‘data.results.map’, so ‘data.map’ but just results in a error says data.map is not a function…I guess because data is an object not an array. But results is an array so I am still lost. I do think the issue lies here somewhere though…