Created
August 16, 2020 18:18
-
-
Save simicd/563e39235f241c48ebc6c4debe2d2af5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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