Skip to content

Instantly share code, notes, and snippets.

@brunocarvalhodearaujo
Last active December 17, 2018 15:45
Show Gist options
  • Save brunocarvalhodearaujo/564ba068a884c483f4624472e3701718 to your computer and use it in GitHub Desktop.
Save brunocarvalhodearaujo/564ba068a884c483f4624472e3701718 to your computer and use it in GitHub Desktop.
/**
* Copyright 2018-present Bruno Carvalho de Araujo.
* This source code is licensed under the proprietary license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component, ReactNode, Fragment } from 'react'
import PropTypes from 'prop-types'
type Props = {
children: ReactNode
}
type State = {
suggestions: string[]
}
export default class SuggestionInput extends Component<Props, State> {
static propTypes = {
children: PropTypes.element
}
static defaultProps = {}
state = {
suggestion: '',
suggestions: []
}
search = async (search) => {
try {
const suggestions = await fetch('https://pt.wikipedia.org/w/api.php?&origin=*&action=opensearch&search=Google&limit=5')
.then(response => response.json())
this.setState({ suggestions })
} catch (error) {
this.setState({ suggestions: [] })
}
}
onFieldChange = (event: SyntheticInputEvent<HTMLInputElement>) => {
this.setState({
[ event.currentTarget.name ]: event.currentTarget.value
})
this.search(this.state[event.currentTarget.name ])
}
render () {
const { suggestion, suggestions } = this.state
return (
<Fragment>
<input
type='text'
name='suggestion'
value={suggestion}
onBlur={() => this.search(suggestion)}
onChange={this.onFieldChange}
/>
<pre>{JSON.stringify(suggestions, undefined, 2)}</pre>
</Fragment>
)
}
}
import React, { Component } from 'react'
import $ from 'jquery'
class Search extends Component {
constructor() {
super()
this.state = { suggestions: [] }
}
suggestions(search) {
return $.ajax({
url: 'https://pt.wikipedia.org/w/api.php',
dataType: 'jsonp',
data: {
action: 'opensearch',
format: 'json',
search
}
}).promise()
}
async changeTerm({ target }) {
this.setState({ suggestions: await this.suggestions(target.value) })
}
render() {
return (
<div class="container">
<input type="text" value={this.state.value} onChange={this.changeTerm.bind(this)} />
<pre>{JSON.stringify(this.state.suggestions, undefined, 2)}</pre>
</div>
)
}
}
render(<Search />, document.querySelector('view'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment