Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-select debounced async call not displaying suggestions

I'm using react-select loading the results from an api and debouncing the queries with lodash.debounce:

import React, {useState} from 'react';
import AsyncSelect from 'react-select/lib/Async';
import debounce from 'lodash.debounce';
import {search} from './api';

const _loadSuggestions = (query, callback) => {
  return search(query)
    .then(resp => callback(resp));
};

const loadSuggestions = debounce(_loadSuggestions, 300);

function SearchboxTest() {
  const [inputValue, setInputValue] = useState("");

  const onChange = value => {
    setInputValue(value);
  };

  return (
    <AsyncSelect
      value={inputValue}
      loadOptions={loadSuggestions}
      placeholder="text"
      onChange={onChange}
    />
  )
}

It seems to work fine when I enter something in the searchbox for the first time (query is debounced and suggestions populated correctly), but if I try to enter a new value, a second fetch query is fired as expected, but the suggestions coming from that second call are not displayed (and I don't get the "Loading..." message that react-select displays).

When I don't debounce the call the problem seems to go away (for the first and any subsequent calls):

import React, {useState} from 'react';
import AsyncSelect from 'react-select/lib/Async';
import {search} from '../../api';

const loadSuggestions = (query, callback) => {
  return search(query)
    .then(resp => callback(resp));
};

function SearchboxTest() {
  const [inputValue, setInputValue] = useState("");

  const onChange = value => {
    setInputValue(value);
  };

  return (
    <AsyncSelect
      value={inputValue}
      loadOptions={loadSuggestions}
      placeholder="text"
      onChange={onChange}
    />
  )
}

Any idea what is going on? Any help to understand this issue would be much appreciated.

M;

like image 800
emepyc Avatar asked Mar 09 '19 02:03

emepyc


1 Answers

I was aslo facing the same issue and got this solution.

If you are using callback function, then You DON'T need to return the result from API.

Try removing return keyword from _loadSuggestions function. as shown below

 import React, {useState} from 'react';
 import AsyncSelect from 'react-select/lib/Async';
 import debounce from 'lodash.debounce';
 import {search} from './api';
 
 const _loadSuggestions = (query, callback) => {
   search(query)
     .then(resp => callback(resp));
 };
 
 const loadSuggestions = debounce(_loadSuggestions, 300);
 
 function SearchboxTest() {
   const [inputValue, setInputValue] = useState("");
 
   const onChange = value => {
     setInputValue(value);
   };
 
   return (
     <AsyncSelect
       value={inputValue}
       loadOptions={loadSuggestions}
       placeholder="text"
       onChange={onChange}
     />
   )
 } 
like image 130
Avkash Avatar answered Oct 13 '22 02:10

Avkash