0

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.

1
  • 1
    You might want to have a better understanding about JS this scope and lexical this with ES6. Commented Aug 13, 2018 at 7:46

1 Answer 1

0

In then use either arrow function or bind this

then((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
        )
      });
    }
  })

Because function in then is a callback which will be get called later and in case of normal function ( non arrow function ) this points to object which calls the functions so this inside callback won't point to your AutoComplete class object that's why you're getting error

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. issue got resolved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.