DEV Community

Guru
Guru

Posted on

1

Cats Fatc's Quick project

Hello Dev's Yesterday i Uploded a Counter With Single button for both increment and decrement

*Today * i learned about useEffect littele bit more and it useFull tooo mee so much
by learned knowledge i code a simple random cats Facts website that fetch data from an Api

import { useEffect, useState } from "react";
import "./App.css";
import audio from "./assets/click-sound.mp3";

function App() {
  const [catFact, setCatFact] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [clickSound, setClickSound] = useState(null);

  useEffect(() => {
    // Load the click sound
    const sound = new Audio(audio);
    setClickSound(sound);
  }, []);

  const playClickSound = () => {
    if (clickSound) {
      clickSound.play();
    }
  };

  const fetchData = async () => {
    try {
      setLoading(true);
      const response = await fetch("https://catfact.ninja/fact");
      if (!response.ok) {
        throw new Error("Unable to Fetch Data");
      }
      const data = await response.json();
      setCatFact(data.fact);
      setError(false);
      playClickSound(); // Play sound when fetching data
    } catch (err) {
      setError(true);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="App">
      <h1>Cat Facts</h1>
      <h1 className="Logo">🐈😼😿</h1>
      {loading && <h4 className="loading">Loading Data...⏳</h4>}
      {!loading && catFact && <h4>{catFact}</h4>}
      {error && !loading && <h1 className="error">Error 404 ! 🚫</h1>}
      {!loading && !catFact && !error && <h1>No facts available 😿</h1>}

      <button onClick={fetchData}>Show More Facts</button>
    </div>
  );
}

export default App;


Enter fullscreen mode Exit fullscreen mode

Image description

link for the Site : https://catsfactsrandom.netlify.app/

Here Today i leared How use Api in React and Async and Await
Thank You. dev community

thank you....

Please leave your appreciation by commenting on this post!

Everyone is welcome

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

πŸ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay