-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSearch.js
More file actions
92 lines (79 loc) · 2.38 KB
/
Search.js
File metadata and controls
92 lines (79 loc) · 2.38 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import React from "react"
import PropTypes from "prop-types"
class Search extends React.Component {
constructor(props) {
super(props)
this.state = {
value: ''
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return <div>
Search: <input type="text" value={this.state.value} onChange={this.handleChange}/>
Results: <SearchResults term={this.state.value} />
</div>
}
}
const TitlesOnlyListContainer = ({articles}) => {
return <div>
{articles.map((article) => <li key={article.nid}><a href={article.url}>{article.title}</a></li>)}
</div>
}
TitlesOnlyListContainer.propTypes = {
articles: PropTypes.arrayOf(PropTypes.shape({
nid: PropTypes.number,
title: PropTypes.string,
slug: PropTypes.string,
publishedAt: PropTypes.string,
url: PropTypes.string,
authors: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
slug: PropTypes.string,
})),
ledeImage: PropTypes.shape({
src: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
}),
})),
}
class SearchResults extends React.Component {
constructor(props) {
super(props)
this.state = {
articles: [],
}
}
componentDidUpdate(prevProps) {
if (this.props.term !== prevProps.term || this.props.limit !== prevProps.limit) {
this.fetchArticles()
}
}
componentDidMount() {
this.fetchArticles()
}
articleSearch(term, limit = 20, offset = 0) {
// eslint-disable-next-line max-len
return fetch(`https://newrepublic.com/api/articles?q=${term}&filters[status]=PUBLISHED&fields[0]=id&fields[1]=nid&fields[2]=slug&fields[3]=title&fields[4]=authors.name,slug&fields[6]=publishedAt&fields[7]=status&fields[8]=ledeImage&fields[9]=ledeAltImage&fields[10]=url&fields[11]=urlFull&fields[12]=sponsor&fields[13]=deck&limit=${limit}&offset=${offset}`)
}
fetchArticles() {
this.articleSearch(this.props.term, this.props.limit).then((response) => {
response.json().then((results) => {
console.log(results);
this.setState({articles: results.data.articles})
});
})
}
render() {
return <TitlesOnlyListContainer articles={this.state.articles}/>
}
}
SearchResults.propTypes = {
term: PropTypes.string,
limit: PropTypes.number,
}
export default Search