Sorry for my simple question. I didn't find any wiki or stackOverflow group to ask it...
I'm a beginner in reactJs and I need to display the autosuggestion for cities. The city list is quite big and loaded by ajax from server.
Where can I put the logic of such fetching?
I guess that hook __didComonentMount__ will work only once.
Thanks in advance for your help.
You should use the onSuggestionsFetchRequested prop. Documented here.
Example implementation below and on CodePen.
const getSuggestionValue = (suggestion) => suggestion.name
const renderSuggestion = (suggestion) => (<span>{suggestion.name}</span>)
class Example extends React.Component {
constructor() {
super()
this.state = { value: '', suggestions: [] }
}
onChange = (event, { newValue, method }) => {
this.setState({ value: newValue });
}
onSuggestionsFetchRequested = ({ value }) => {
fetch(`https://swapi.co/api/people/?search=${value}`)
.then(response => response.json())
.then(data => this.setState({ suggestions: data.results }))
}
onSuggestionsClearRequested = () => {
this.setState({ suggestions: [] });
};
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: "Search Star Wars",
value,
onChange: this.onChange
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps} />
);
}
}
Yep, thank you!
You should use the
onSuggestionsFetchRequestedprop. Documented here.Example implementation below and on CodePen.
const getSuggestionValue = (suggestion) => suggestion.name const renderSuggestion = (suggestion) => (<span>{suggestion.name}</span>) class Example extends React.Component { constructor() { super() this.state = { value: '', suggestions: [] } } onChange = (event, { newValue, method }) => { this.setState({ value: newValue }); } onSuggestionsFetchRequested = ({ value }) => { fetch(`https://swapi.co/api/people/?search=${value}`) .then(response => response.json()) .then(data => this.setState({ suggestions: data.results })) } onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); }; render() { const { value, suggestions } = this.state; const inputProps = { placeholder: "Search Star Wars", value, onChange: this.onChange }; return ( <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} getSuggestionValue={getSuggestionValue} renderSuggestion={renderSuggestion} inputProps={inputProps} /> ); } }
Btw those looking to try this. The link has changed to https://swapi.dev/api/people/?search=${value}
Most helpful comment
You should use the
onSuggestionsFetchRequestedprop. Documented here.Example implementation below and on CodePen.