Skip to content

Instantly share code, notes, and snippets.

@MoMoWongHK
Created March 7, 2020 18:05
Show Gist options
  • Save MoMoWongHK/98576836bcc194aa56624919e07ea084 to your computer and use it in GitHub Desktop.
Save MoMoWongHK/98576836bcc194aa56624919e07ea084 to your computer and use it in GitHub Desktop.
Source code for Integrating React-Select and Firebase firestore for text-searching
import React, {Component} from 'react'
import AsyncSelect from 'react-select/async';
import firebase from './firebase'
const db = firebase.firestore();
class App extends Component {
constructor(props) {
super(props);
this.state = {
selectedTag: []
}
}
loadOptions = async (inputValue) => {
inputValue = inputValue.toLowerCase().replace(/\W/g, "");
return new Promise((resolve => {
db.collection('Tag')
.orderBy('plainName')
.startAt(inputValue)
.endAt(inputValue + "\uf8ff")
.get()
.then(docs => {
if (!docs.empty) {
let recommendedTags = []
docs.forEach(function (doc) {
const tag = {
value: doc.id,
label: doc.data().tagName
}
recommendedTags.push(tag)
});
return resolve(recommendedTags)
} else {
return resolve([])
}
})
})
)
}
handleOnChange = (tags) => {
this.setState({
selectedTag: [tags]
})
}
render() {
return (
<div>
<AsyncSelect
loadOptions={this.loadOptions}
onChange={this.handleOnChange}
/>
<p>Selected Tag:</p>
{
this.state.selectedTag.map(e => {
return (
<li key={e.value}>
{e.label}
</li>
)
})
}
</div>
);
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment