Skip to content

Instantly share code, notes, and snippets.

@rehrumesh
Created July 5, 2020 07:32
Show Gist options
  • Save rehrumesh/02892a04fe88d2159a9aad8f7ecc0c1a to your computer and use it in GitHub Desktop.
Save rehrumesh/02892a04fe88d2159a9aad8f7ecc0c1a to your computer and use it in GitHub Desktop.
RandomCat component
import React, { useState, useEffect } from "react";
export default function RandomCat() {
const [randomCatImg, setRandomCatImg] = useState(null);
const fetchRandomCat = () => {
setRandomCatImg("");
fetch(`https://aws.random.cat/meow`)
.then((res) => res.json())
.then((catInfo) => {
setRandomCatImg(catInfo.file);
});
};
useEffect(() => {
if (randomCatImg === null) {
fetchRandomCat();
}
});
return (
<div>
<header>
<h3>Cat of the day</h3>
<div>
<button onClick={() => fetchRandomCat()}>New Cat</button>
</div>
{randomCatImg !== "" ? (
<div>
<img src={randomCatImg} width="400px" alt="Cat" />
</div>
) : (
<div>Loading Image</div>
)}
</header>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment