From 41a86494f3caea96dd4ed32733310783e47b429d Mon Sep 17 00:00:00 2001 From: Wes Bos Date: Thu, 5 Apr 2018 16:52:40 -0400 Subject: refactor --- frontend/components/Search.js | 118 ++++++++++++++++++++---------------------- 1 file changed, 56 insertions(+), 62 deletions(-) (limited to 'frontend/components/Search.js') diff --git a/frontend/components/Search.js b/frontend/components/Search.js index b8816ec..49c5023 100644 --- a/frontend/components/Search.js +++ b/frontend/components/Search.js @@ -1,9 +1,8 @@ import Downshift from 'downshift'; -import { Query } from 'react-apollo'; import Router from 'next/router'; import styled from 'styled-components'; import debounce from 'lodash.debounce'; - +import { client } from '../lib/withData'; import { SEARCH_ITEMS_QUERY } from '../queries'; function routeToItem(item) { @@ -43,77 +42,72 @@ const SearchStyles = styled.div` padding: 10px; border: 0; font-size: 2rem; + &.loading { + background: red; + } } `; -function AutoComplete(props) { - const { items, onChange, loading } = props; - return ( - (i === null ? '' : i.title)}> - {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex }) => ( -
- {/* This is the searchInput */} - {loading && 'LOADING'} - { - props.refetch({ searchTerm: e.target.value }); - }, - })} - /> - {isOpen ? ( - - {/* This is the Dropdown */} - {items.map((item, index) => ( - - {item.title} - {item.title} - - ))} - {!items.length && Nothing Found for {inputValue}...} - - ) : null} -
- )} -
- ); -} - -// TODO: This should not fire a queryon page load -class Search extends React.Component { +class AutoComplete extends React.Component { state = { - skip: true, + items: [], + loading: false, }; - componentDidMount() { - this.setState({ skip: false }); - } + onChange = debounce(async e => { + if (!e.target.value) { + return this.setState({ items: [] }); + } + this.setState({ loading: true }); + const res = await client.query({ + query: SEARCH_ITEMS_QUERY, + variables: { searchTerm: e.target.value }, + }); + this.setState({ items: res.data.items, loading: false }); + }, 350); + render() { return ( - - {({ data, error, loading, refetch }) => - console.log('QUERY', data.items) || ( - (i === null ? '' : i.title)}> + {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex }) => ( +
+ {/* This is the searchInput */} + { + e.persist(); + this.onChange(e); + }, + })} /> - )} - + {/* This is the Dropdown */} + {isOpen && ( + + {this.state.items.map((item, index) => ( + + {item.title} + {item.title} + + ))} + {/* Found Nothing State */} + {!this.state.items.length && ( + Nothing Found for {inputValue}... + )} + + )} +
+ )} +
); } } -export default Search; +export default AutoComplete; -- cgit v1.3