Am trying to place autosuggest with api result.
import React, { Component } from "react";
import Autosuggest from "react-autosuggest";
import axios from "axios";
// When suggestion is clicked, Autosuggest needs to populate the input
// based on the clicked suggestion. Teach Autosuggest how to calculate the
// input value for every given suggestion.
const getSuggestionValue = suggestion => suggestion.city;
// Use your imagination to render suggestions.
const renderSuggestion = suggestion => <div>{suggestion.city}</div>;
class Autocomplete extends React.Component {
constructor(props) {
super(props);
this.state = {
value: "",
suggestions: []
};
this.getData = this.getData.bind(this);
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
getData(value) {
var itemslist = {};
axios
.get(
"https://abcdgf/api/cities?page=1&perPage=1000&search=" +
value
)
.then(function(response) {
console.log(response.status);
if (response.status === 200) {
itemslist = response.data.data;
console.log(itemslist);
this.setState({
suggestions: itemslist.filter(
lang => lang.city.toLowerCase().slice(0, value.length) === value
)
});
}
})
.catch(function(error) {
console.log(error);
});
}
// Autosuggest will call this function every time you need to update suggestions.
// You already implemented this logic above, so just use it.
onSuggestionsFetchRequested = ({ value }) => {
if (value.length > 2) {
this.getData(value.trim().toLowerCase());
}
};
// Autosuggest will call this function every time you need to clear suggestions.
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
render() {
const { value, suggestions } = this.state;
// Autosuggest will pass through all these props to the input.
const inputProps = {
placeholder: "Type a programming language",
value,
onChange: this.onChange
};
// Finally, render it!
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
/>
);
}
}
export default Autocomplete;
At line no 49 in getData function, its giving an error saying that Cannot read property 'setState' of undefined. Actually getData is declared in constructor. If i remove this axios then it is working properly. please let me know what is the error in this. thanks in advance.
thisscope andlexical thiswith ES6.