-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathclass.jsx
More file actions
65 lines (57 loc) · 1.32 KB
/
class.jsx
File metadata and controls
65 lines (57 loc) · 1.32 KB
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
/* eslint-disable react/prop-types */
import React, {Component} from 'react';
const searchForChuckJokes = async query => {
try {
const result = await fetch(`https://api.chucknorris.io/jokes/search?query=${query}`);
const resultJSON = await result.json();
return resultJSON.result || [];
} catch (error) {
console.error(error);
return [];
}
};
export class JokeList extends Component {
state = {
searching: false,
jokes: null
}
componentDidMount() {
this._handleNewSearch();
}
componentDidUpdate(prevProps) {
if (prevProps.query !== this.props.query) {
this._handleNewSearch();
}
}
_handleNewSearch = async() => {
const {query} = this.props;
if (!query) {
return;
}
this.setState({searching: true});
const jokes = await searchForChuckJokes(query);
this.setState({
searching: false,
jokes
});
}
render() {
const {searching, jokes} = this.state;
if (searching) {
return (<div className="chuck-jokes--loader">Searching...</div>);
}
if (!jokes) {
return null;
}
return (
<>
<h2>Found {jokes.length} results</h2>
{jokes.map(item => (
<div className="chuck-jokes--item" key={item.id}>
{item.value}
</div>
))}
</>
);
}
}