0

I am using react-autosuggest I try to fetch the results from the server

getSuggestions (value) {
  const escapedValue = escapeRegexCharacters(value.trim());

  if (escapedValue === '') {
  return [];
  }

  const regex = new RegExp('^' + escapedValue, 'i');
    if (!value) {
        return Promise.resolve(myArr);
    }
  fetch(`/mypoint`)
    .then((response) => response.json())
    .then((users) => {
    if (users == undefined) {

      return []
    } else {

      return users
    }
    })
  .catch(err => {
    console.log(err)
  })


 }

This returns users from server when i console log it, no problem

  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      isLoading: false,
      suggestions: this.getSuggestions(value),
    });
  };

This gets suggested values from the above function however when I write a word to input field

The prop suggestions is marked as required in Autosuggest, but its value is undefined.

I get suggestions as undefined even though it console the returned values from the server

So the return inside fetch returns undefined what should I do any suggestions!

2
  • where do you render your component ? Commented Apr 3, 2018 at 10:48
  • Inside the same component as the functions Commented Apr 3, 2018 at 10:50

1 Answer 1

1

Its asynchronous API handling issue.In getSuggestions,you are returning nothing.return statement inside fetch callback will not return to onSuggestionsFetchRequested for setState.By default getSuggestions returning undefined.

Solutions:

Either you do

  1. promise chaining or
  2. pass callback whichever you find better.

Solution using callback:

function getSuggestions(value, callback) {

      return fetch(`/mypoint`).then((response) => response.json()).then((users) => {
        if (users == undefined) {

          callback(null, []);
        } else {

          callback(null, users);
        }
      }).catch(err => {
        callback(err);
      })

    }

function : onSuggestionsFetchRequested

onSuggestionsFetchRequested = ({value}) => {

  getSuggestions = (value, (err, data) => {
    this.setState({isLoading: false, suggestions: data});
  });

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

1 Comment

@Kaan please upvote and accept it if it's working for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.