React that fetch

import React, { useState, useEffect } from "react";

const CatFact = () => {
  const [catFact, setCatFact] = useState("");

  useEffect(() => {
    // Fetch a random cat fact when the component loads
    const fetchCatFact = async () => {
      try {
        const response = await fetch("https://catfact.ninja/fact");
        const data = await response.json();
        setCatFact(data.fact); // Update the state with the cat fact
      } catch (error) {
        console.error("Error fetching the cat fact:", error);
      }
    };

    fetchCatFact();
  }, []); // Empty dependency array ensures this runs only once when the component mounts

  return (
    <div className="cat-fact-container">
      <h1>Random Cat Fact</h1>
      {catFact ? (
        <p>{catFact}</p>
      ) : (
        <p>Loading cat fact...</p>
      )}
    </div>
  );
};

export default CatFact;

Comments

Popular posts from this blog

Petroleum