Skip to content

Instantly share code, notes, and snippets.

@snigo
Last active February 27, 2024 16:55
Show Gist options
  • Save snigo/1962a0609a837276a3fb6e8d589794c7 to your computer and use it in GitHub Desktop.
Save snigo/1962a0609a837276a3fb6e8d589794c7 to your computer and use it in GitHub Desktop.
function getRandom() {
return fetch("https://api.quotable.io/random").then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch quote");
}
return response.json();
});
}
let initialized = false;
function QuoteOfTheDay() {
const [quote, setQuote] = useState("");
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
if (!initialized) {
initialized = true;
getRandom
.then((data) => {
setQuote(data.content);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setIsLoading(false);
});
}
return (
<main className={styles.main}>
<h1>Quote of the Day</h1>
{isLoading ? (
<p>Loading...</p>
) : error ? (
<p>Error: {error.message}</p>
) : (
<blockquote>
<p>{quote}</p>
</blockquote>
)}
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment