Home > Net >  Fetching data Next.js and Typescript using getStaticProps
Fetching data Next.js and Typescript using getStaticProps

Time:12-18

I am doing a personal project on Next.js with TypeScript. I am trying to fetch an api and then to do a map of the items, but I cannot make it work. I did a console.log and it gives undefined. I did put the file on the pages folder. This is the code:

import { InferGetStaticPropsType } from 'next'

type Data = {
    id: string
    films: string
    people: string
    planets: string
    species: string
    vehicles: string
 }

export const getStaticProps = async () => {
    const res = await fetch('https://www.swapi.tech/api/')
    const swapis: Data[] = await res.json()
  
    return {
        props: {
          swapis,
        },
    } 
}
 
const FilmList = ({ swapis }: InferGetStaticPropsType<typeof getStaticProps>) => {
    console.log('swapis', swapis)
    return (
        <>
        <h2>List of Films</h2>
        {swapis.map((swapi) => (
            <ul key={swapi.id}>
                <li>{swapi.films}</li>
            </ul>
        ))}
        </>
    );
}
 
export default FilmList;

CodePudding user response:

Your Data type is wrong. You're calling https://www.swapi.tech/api/ which returns

{
  "message": "ok",
  "result": {
    "films": "https://www.swapi.tech/api/films",
    "people": "https://www.swapi.tech/api/people",
    "planets": "https://www.swapi.tech/api/planets",
    "species": "https://www.swapi.tech/api/species",
    "starships": "https://www.swapi.tech/api/starships",
    "vehicles": "https://www.swapi.tech/api/vehicles"
  }
}

Full working example:

import { InferGetStaticPropsType } from 'next';

type Data = {
  message: string;
  result: {
    id: string;
    films: string;
    people: string;
    planets: string;
    species: string;
    vehicles: string;
  };
};

export const getStaticProps = async () => {
  const res = await fetch('https://www.swapi.tech/api/');
  const swapis: Data = await res.json();

  return {
    props: {
      swapis,
    },
  };
};

const FilmList = ({ swapis }: InferGetStaticPropsType<typeof getStaticProps>) => {
  return (
    <>
      <h2>List of Films</h2>
      {Object.entries(swapis.result).map(([key, value]) => (
        <ul key={key}>
          <li>{value}</li>
        </ul>
      ))}
    </>
  );
};

export default FilmList;
  • Related