-
Notifications
You must be signed in to change notification settings - Fork 0
/
BookSearch.js
108 lines (89 loc) · 2 KB
/
BookSearch.js
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import PropTypes from 'prop-types'
import * as BooksAPI from './BooksAPI'
import Book from './Book'
class BookSearch extends Component {
static PropTypes = {
books: PropTypes.array,
updateBook: PropTypes.func
}
state = {
query: '',
books: []
}
// Populate the books array in state with the search results (and the current books in the book shelf)
setBooks = (searchResults) => {
this.props.books.forEach((book) => {
let match = searchResults.find((result) => result.id === book.id)
if (match)
{
match.shelf = book.shelf
}
})
this.setState(() => ({
books: searchResults
}))
}
// Generate books based on the given search query
searchBooks = (query) => {
BooksAPI.search(query)
.then((books) => {
if (books.error === 'empty query')
{
this.setBooks([])
}
else
{
this.setBooks(books)
}
})
}
// Update the query string in state based on the Controlled Input
updateQuery = (query) => {
this.setState(() => ({
query
}),
() => {
if (query)
{
this.searchBooks(query)
}
else
{
this.setBooks([])
}
})
}
render() {
const { query } = this.state
return (
<div className="search-books">
<div className="search-books-bar">
<Link className="close-search" to="/">Close</Link>
<div className="search-books-input-wrapper">
<input
type="text"
placeholder="Search by title or author"
value={query}
onChange={(event) => this.updateQuery(event.target.value)}
/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{this.state.books.length > 0 && (
this.state.books.map((book) => (
<li key={book.id}><Book book={book} updateBook={this.props.updateBook} /></li>
))
)}
{this.state.books.length < 1 && (
<li>No Results</li>
)}
</ol>
</div>
</div>
);
}
}
export default BookSearch