Created
March 29, 2021 00:38
-
-
Save jeffminnear/0851dc5ec2aabd4ce51dff8845a19284 to your computer and use it in GitHub Desktop.
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 from 'react'; | |
import { Avatar } from '@material-ui/core'; | |
import { Suspense } from 'react'; | |
const fetchUrl = 'https://dog.ceo/api/breeds/image/random'; | |
async function getImage() { | |
const response = await fetch(fetchUrl); | |
const data = await response.json(); | |
return data.message; | |
}; | |
function wrapPromise(promise) { | |
let status = 'pending'; | |
let response; | |
let suspender = promise.then( | |
result => { | |
status = 'success'; | |
response = result; | |
}, | |
err => { | |
status = 'error'; | |
response = err; | |
} | |
); | |
return { | |
read() { | |
switch (status) { | |
case 'pending': | |
throw suspender; | |
case 'error': | |
throw response; | |
case 'success': | |
return response; | |
} | |
} | |
} | |
} | |
const fetchImage = () => { | |
return wrapPromise(getImage()); | |
} | |
function DogImage({ image }) { | |
const imgSrc = image.read(); | |
return ( | |
<Avatar | |
src={imgSrc} | |
style={{ | |
height: '200px', | |
width: '200px', | |
}} | |
/> | |
); | |
} | |
function FallBack() { | |
return ( | |
<p | |
style={{ | |
textAlign: 'center', | |
fontSize: '20px', | |
color: 'black', | |
position: 'relative', | |
left: '-20%', | |
}} | |
> | |
Searching for good boys and girls... | |
</p> | |
); | |
} | |
export default function Image() { | |
return ( | |
<Suspense fallback={FallBack()}> | |
<DogImage | |
image={fetchImage()} | |
/> | |
</Suspense> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment