Skip to content

Instantly share code, notes, and snippets.

@gje4
Created April 9, 2019 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gje4/479fab9aeeb8631ef56db30e5ba5bc9d to your computer and use it in GitHub Desktop.
Save gje4/479fab9aeeb8631ef56db30e5ba5bc9d to your computer and use it in GitHub Desktop.
import _ from 'lodash'
import React, { Component } from 'react'
import { Search, Grid, Header, Segment } from 'semantic-ui-react'
import { getProducts } from '../lib/moltin'
export default class SearchExampleStandard extends Component {
constructor(props) {
super()
this.state = {
searchSource: []
}
}
async componentDidMount() {
const { data, included } = await getProducts()
const products = data.map(product => {
const imageId = product.relationships.main_image
? product.relationships.main_image.data.id
: false
return {
title: product.name,
description: product.description,
description: product.description,
image: imageId
? included.main_images.find(img => img.id === imageId).link.href
: '/static/moltin-light-hex.svg',
price: String(product.price[0].amount / 100)
}
})
this.setState({ searchSource: products })
console.log('search', this.state.searchSource)
}
componentWillMount() {
this.resetComponent()
}
resetComponent = () =>
this.setState({ isLoading: false, results: [], value: '' })
handleResultSelect = (e, { result }) => this.setState({ value: result.title })
handleSearchChange = (e, { value }) => {
this.setState({ isLoading: true, value })
setTimeout(() => {
if (this.state.value.length < 1) return this.resetComponent()
const re = new RegExp(_.escapeRegExp(this.state.value), 'i')
const isMatch = result => re.test(result.title)
this.setState({
isLoading: false,
results: _.filter(this.state.searchSource, isMatch)
})
}, 300)
}
render() {
const { isLoading, value, results } = this.state
console.log('search results', results)
return (
<Grid>
<Grid.Column width={6}>
<Search
loading={isLoading}
onResultSelect={this.handleResultSelect}
onSearchChange={_.debounce(this.handleSearchChange, 500, {
leading: true
})}
results={results}
value={value}
{...this.props}
/>
<img class="impreseePhoto" src="img/Foto.svg" />
</Grid.Column>
</Grid>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment