-
-
Save MoMoWongHK/98576836bcc194aa56624919e07ea084 to your computer and use it in GitHub Desktop.
Source code for Integrating React-Select and Firebase firestore for text-searching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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