Home > Mobile >  I can't Fetch data in nextjs from an external API
I can't Fetch data in nextjs from an external API

Time:10-04

I'm trying to show a fact about cats in the page, this fact comes from this api 'https://catfact.ninja/fact'.

My code is:

import Head from 'next/head';
import styles from '../styles/Home.module.css';

export const getSataticProps = async () => {
  const res = await fetch('https://catfact.ninja/fact');
  const data = await res.json();

  return {
    props: { home: data },
  };
};

const Home = ({ home }) => {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>Let's see fun facts about cats</h1>
        {home?.map((fact) => (
          <div key={fact}>
            <p>{fact.fact}</p>
          </div>
        ))}
      </main>
    </div>
  );
};
export default Home;

but the result doesn't show the fact enter image description here

CodePudding user response:

You have a typo. Change getSataticProps to getStaticProps

Also, it looks like the https://catfact.ninja/fact endpoint returns an object, not an array; so you should not home.map in your component.

Do this instead:

const Home = ({ home }) => {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1 className={styles.title}>Let's see a fun fact about cats</h1>
        <p>{home.fact}</p>
      </main>
    </div>
  );
};
  • Related