Created
July 5, 2020 07:32
-
-
Save rehrumesh/02892a04fe88d2159a9aad8f7ecc0c1a to your computer and use it in GitHub Desktop.
RandomCat component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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