Skip to content

Instantly share code, notes, and snippets.

@frankfaustino
Last active January 22, 2018 19:24
Show Gist options
  • Save frankfaustino/9599295d5b863f0a6f8a9228c8d51759 to your computer and use it in GitHub Desktop.
Save frankfaustino/9599295d5b863f0a6f8a9228c8d51759 to your computer and use it in GitHub Desktop.
Search Function from bookvote Project
import React, { Component } from 'react';
import SearchResult from './SearchResult.js';
import url from '../../config';
import axios from 'axios';
class Search extends Component {
constructor() {
super();
this.state = {
filter: 'SUBJECT',
search: '',
response: null
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
const value = e.target.type === 'text' ? e.target.value : e.target.value;
const name = e.target.name;
this.setState({ [name]: value });
}
async handleSubmit(e) {
try {
if (e.which === 13) {
let res = await axios.get(`${url}/API/Search/${this.state.filter}/${this.state.search}`)
this.setState({ response: res.data });
}
} catch (e) {
console.error(e);
}
}
createSearchResults(res) {
return res.map(e => <SearchResult results={e} key={e._id} />);
}
render() {
return (
<div className="Search">
<header className="Search-header">
<h1 className="Search-title" style={{display: 'inline'}}>Search books</h1>
<div className="form" style={{ marginBottom: '10px',display: 'inline' }}>
<input
name="search"
type="text"
value={this.state.search}
onChange={this.handleChange}
onKeyDown={this.handleSubmit}
/>
<select
name="filter"
value={this.state.filter}
onChange={this.handleChange}
>
<option value="SUBJECT">Subject</option>
<option value="TITLE">Title</option>
<option value="AUTHOR">Author</option>
<option value="ISBN">ISBN</option>
</select>
</div>
</header>
{this.state.response
? this.state.response.hasOwnProperty('RESPONSE')
? null
: this.createSearchResults(this.state.response)
: null}
</div>
);
}
}
export default Search;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment