Skip to content

Instantly share code, notes, and snippets.

@simicd
Created August 16, 2020 18:18
Show Gist options
  • Save simicd/563e39235f241c48ebc6c4debe2d2af5 to your computer and use it in GitHub Desktop.
Save simicd/563e39235f241c48ebc6c4debe2d2af5 to your computer and use it in GitHub Desktop.
// DogImage.tsx
import React, { FC, useState, useEffect } from "react";
export const DogImage: FC = () => {
type DogImageType = { message: string; status: string };
const [data, setData] = useState<DogImageType>();
useEffect(() => {
// Define asynchronous function - since useEffect hook can't handle async directly,
// a nested function needs to be defined first and then called thereafter
const fetchData = async () => {
try {
// Fetch data from REST API
const response = await fetch("https://dog.ceo/api/breed/beagle/images/random");
if (response.status === 200) {
// Extract json
const rawData: DogImageType = await response.json();
setData(rawData);
} else {
console.error(`Error ${response.status} ${response.statusText}`);
}
} catch (error) {
console.error(`Error ${error}`);
}
};
// Call async function
fetchData();
}, []);
return <>{data ? <img src={data.message}></img> : <div>Loading</div>}</>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment