react-select icon indicating copy to clipboard operation
react-select copied to clipboard

Debouncing support

Open radar opened this issue 11 years ago • 49 comments

Hi there, I was wondering there is a way to "debounce" async option loading with react-select. Currently, I'm seeing queries like this:

image

I would like react-select to only query after a 250ms typing pause. What do I need to do to make react-select do this? I have tried wrapping my function in a setTimeout, but that does not appear to do anything:

  taxons (input, callback) {
    setTimeout(function () {
      $.ajax({
        url: '/api/v2/taxons/search',
        dataType: 'json',
        cache: false,
        data: { name: input },
        success: function (response) {
          var options = response.data.map(function(taxon, index) {
            return (
              { value: taxon.id, label: taxon.attributes.tree_name }
            );
          });

          callback(null, {
            options: options
          })
        }
      })
    }, 250)
  }

radar avatar Nov 23 '15 03:11 radar

@radar You could replace your setTimeout call with Lodash's _.debounce(func, 250). Documentation at https://lodash.com/docs#debounce

MrLeebo avatar Nov 23 '15 17:11 MrLeebo

Rather, _.throttle(func, 250) is probably more appropriate for this case.

MrLeebo avatar Nov 23 '15 17:11 MrLeebo

(On my phone so bear with me)

IIRC, wrapping the asynchronous call in a denounce or throttle meant that the loading spinner remained after a page load. It's like whatever it is returning, react-select doesn't like it and so it shows the spinner instead.

Hopefully tomorrow I will get some time to get back to this code and give you some more hard data on it.

Just wanted to post this today so it doesn't look like I've fired and forgot.

On 24 Nov 2015, at 04:02, Jeremy Liberman [email protected] wrote:

Rather, _.throttle(func, 250) is probably more appropriate for this case.

— Reply to this email directly or view it on GitHub.

radar avatar Nov 25 '15 06:11 radar

That's a good point, the callback function can't really be throttled. You could try switching to Promises https://github.com/JedWatson/react-select#user-content-async-options-with-promises

And from there you can return the same promise for repeated calls. There are a number of options that come up when I search for "debounce promises" but I can't offer any specific recommendations for you since it's not something I've tried.

MrLeebo avatar Nov 25 '15 14:11 MrLeebo

Thanks @MrLeebo, do you have an example of pairing that with debouncing?

radar avatar Nov 26 '15 01:11 radar

You can use es6-promise-debounce.

<Select.Async
...
loadOptions={debounce(this.getItem, 500)}
... />

marcelometal avatar Apr 11 '16 00:04 marcelometal

Has anyone got deBounce working?

@marcelometal version seems to lose the events, the function gets called but the menu is never populated. I assume the synthetic event is getting lost.

Any ideas?

Thanks.

ghost avatar Aug 29 '16 20:08 ghost

@grandmore I've got debouncing working. The key is to make sure that lodash's debounce method is evaluated exactly once.

Suppose you have a function fetch that retrieves the options for you and returns a Promise. You can then create a debounced version of this function like:

const debouncedFetch = debounce((searchTerm, callback) => {
  fetch(searchTerm)
    .then((result) => callback(null, {options: result})
    .catch((error) => callback(error, null));
}, 500);

This debouncedFetch function can then be passed to the Select.Async component:

<Select.Async
  ...
  loadOptions={debouncedFetch}
  ...
/>

Note that you cannot inline the debouncedFetch function in the render function of your component. If you do this, lodash's debounce would be called whenever the component is rerendered. This breaks the debounce function.

Hope this helps.

irundaia avatar Sep 01 '16 08:09 irundaia

Thanks @irundaia this worked perfectly. Appreciate your help.

There is a missing bracket in your code, here is the corrected one for anyone else that needs it.

const debouncedFetch = _.debounce((searchTerm, callback) => {
  search(searchTerm)
    .then((result) => callback(null, { options: result }))
    .catch((error) => callback(error, null));
}, 500);

ghost avatar Sep 01 '16 08:09 ghost

In case anyone runs into a similar use case to me: I have three react-select fields within the same form and each of them had to run different debounced async functions (using lodash's debounce). I had to declare the component as a class and set the debounce in the constructor:

class TargetingPage extends Component {
  constructor(props) {
    super(props);
    this.fetchA = debounce(this.fetchA.bind(this), 450);
    this.fetchB = debounce(this.fetchB.bind(this), 450);
    this.fetchC = debounce(this.fetchC.bind(this), 450);
  }

  fetchA(query, callback) {
    const { customProp, searchFbGeoLocationTargets } = this.props;
    searchFbGeoLocationTargets(query, fbAccessToken, callback);
  }

  fetchB(query, callback) {
    const { fbAccessToken, searchFbLocales } = this.props;
    searchFbLocales(query, fbAccessToken, callback);
  }

  fetchC(query, callback) {
    const { fbAccessToken, searchFbInterests, adAccount } = this.props;
    searchFbInterests(query, fbAccessToken, callback, adAccount.providerParams.id);
  }

  render() {
    ...pass this.fetchA, this.fetchB and this.fetchC into onLoadOptions prop...
  }
}

jonahlau avatar Feb 25 '17 10:02 jonahlau

Just to add to what @MrLeebo said, _.throttle works better for me in this case than _.debounce

powmedia avatar Sep 14 '17 11:09 powmedia

Hi @irundaia !

Is debounce the same as _.debounce (lodash)?

danvc avatar Nov 14 '17 23:11 danvc

@DanZeuss it is lodash’s debounce indeed.

irundaia avatar Nov 14 '17 23:11 irundaia

hello on the docs there is no callback; why you do use it ?

const getOptions = (input) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

I have a doubt, how i can add a new parameter custolimized to getOptions ? i need to send the name of a table.


<Async
  name="form-field-name"
  value="one"
  loadOptions={getOptions}
/>

by example:

const getOptions = (input, tablename) => {
  return fetch(`/users/${input}.json`)
    .then((response) => {
      return response.json();
    }).then((json) => {
      return { options: json };
    });
}

I have a doubt, how i can add a new parameter custolimized to getOptions ? i need to send the name of a table.


let tablename='customer'

<Async
  name="form-field-name"
  value="one"
  loadOptions={getOptions(tablename)}
/>

but does not work... any idea?

webmobiles avatar Jan 16 '18 15:01 webmobiles

@webmobiles This question isn't relevant to this issue at all. You should consider stack overflow or some other resource for learning JS. However, your function can return another function:

const generateOptionsFunc = tablename => input => {
  return fetch(`/${tablename}/${input}.json`)
    .then(res => res.json())
    .then(json => ({ options: json }))
}

// ...

const loadOptions = generateOptionsFunc("users")
 
// ...

<Async
  name="form-field-name"
  value="one"
  loadOptions={loadOptions}
/>

MrLeebo avatar Jan 16 '18 16:01 MrLeebo

@MrLeebo thanks, i did not realize that. you saved my day, but that is a wrapper not? or decorator?

webmobiles avatar Jan 16 '18 16:01 webmobiles

I think the term you're looking for is "higher-order function".

MrLeebo avatar Jan 16 '18 19:01 MrLeebo

Is this really working for people? For you @grandmore ? https://github.com/JedWatson/react-select/issues/614#issuecomment-244006496

morgs32 avatar Jan 30 '18 21:01 morgs32

A built-in debounce prop on the Async component would be a very welcome change.

paulirwin avatar Feb 22 '18 15:02 paulirwin

@morgs32 I tried to use debounce and it keeps failing for me as well. The call is made according to the time out but the menu does not get populated and the loader continues to show in the screen. Where you able to figure out a workaround?

dineshdeiveegan avatar Mar 30 '18 05:03 dineshdeiveegan