0

function getSuggestions(inputValue) {
  let results = [];
  axios.get(`${API_URL}?queryString=${inputValue}`)
    .then(({ data }) => {
      results = data;
    })
  let textValues = results.map(r => (textValues.push(r.text.toUpperCase())));
  //push all unique values to Set
  let uniqSet = new Set(textValues);
  //turn Set into Array object
  let uniqArr = Array.from(uniqSet)
  let suggestions = uniqArr.map(r => (suggestions.push({'label': r.text.toUpperCase()})));
  return suggestions.filter(suggestion => {
    const keep =
      (!inputValue || suggestion.label.toLowerCase().includes(inputValue.toLowerCase())) &&
      count < 5;

    if (keep) {
      count += 1;
    }

    return keep;
  });
}

I have this function to create an auto-complete search component where I take an inputValue entered by the user and send it to an endpoint which then returns an object of search terms.

I am attempting to set this empty results array to the data object that is returned from my fetch with axios. No matter what I try though, the results array always stays empty. Any suggestions? Thank you in advance.

salols
  • 89
  • 1
  • 2
  • 10

1 Answers1

1

The axios code is asynchronous, the rest of your code is not (and is not waiting for the asynchronous code). Your best bet is to use async/await if you don't need to support older browsers

async function getSuggestions(inputValue) {
  let results = await axios.get(`${API_URL}?queryString=${inputValue}`).then(({ data }) => data)
  let textValues = results.map(r => (textValues.push(r.text.toUpperCase())));
  //push all unique values to Set
  let uniqSet = new Set(textValues);
  //turn Set into Array object
  let uniqArr = Array.from(uniqSet)
  let suggestions = uniqArr.map(r => (suggestions.push({'label': r.text.toUpperCase()})));
  return suggestions.filter(suggestion => {
    const keep =
      (!inputValue || suggestion.label.toLowerCase().includes(inputValue.toLowerCase())) &&
      count < 5;

    if (keep) {
      count += 1;
    }

    return keep;
  });
}

Otherwise your function will probably need to return a promise since the result is asynchronous:

function getSuggestions(inputValue) {
  return axios.get(`${API_URL}?queryString=${inputValue}`).then(({ data }) => {
    let textValues = data.map(r => (textValues.push(r.text.toUpperCase())));
    //push all unique values to Set
    let uniqSet = new Set(textValues);
    //turn Set into Array object
    let uniqArr = Array.from(uniqSet)
    let suggestions = uniqArr.map(r => (suggestions.push({'label': r.text.toUpperCase()})));
    return suggestions.filter(suggestion => {
      const keep =
        (!inputValue || suggestion.label.toLowerCase().includes(inputValue.toLowerCase())) &&
        count < 5;

      if (keep) {
        count += 1;
      }

      return keep;
    });
  })  
}

getSuggestions('test').then(keep => {
  // do something with response
})
Rob M.
  • 35,491
  • 6
  • 51
  • 50