-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathkitties.jsx
70 lines (60 loc) · 1.67 KB
/
kitties.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React from 'react';
import './kitties.css';
import Spinner from '../components/spinner';
// Exercise 2
//
// Here is the standard way of fetching the API for the cat images and then
// displaying them, while the spinner is shown until the image is downloaded
//
// Your tasks is to rewrite this so that it uses Suspense and react-cache:
// import {unstable_createResource as createResource} from 'react-cache';
// to achieve the same functionality
//
// 15 minutes, then we will do it together
// Check the "network" in developer tools when done
const KittyImage = ({src}) => (
<img src={src} alt="random kitty" />
);
export default class Kitties extends React.Component {
state = {
isLoading: false,
url: ''
}
componentDidMount = () => {
this._fetchNewKitty();
};
_fetchNewKitty = async() => {
this.setState({
isLoading: true
});
const response = await fetch('https://api.thecatapi.com/v1/images/search');
const [result] = await response.json();
const img = new Image();
const src = await new Promise(resolve => {
img.onload = () => resolve(result.url);
img.src = result.url;
});
this.setState({
isLoading: false,
url: src
});
}
_handleButtonClick = () => {
this._fetchNewKitty();
}
render = () => {
const {isLoading, url} = this.state;
if (isLoading) {
return <Spinner>Loading the kitty...</Spinner>
}
return (
<div className="kitties">
<button onClick={this._handleButtonClick}>Show Another Kitty</button>
{isLoading
? <Spinner>Loading the kitty...</Spinner>
: <KittyImage src={url} />
}
</div>
);
}
}