JedWatson / react-select

The Select Component for React.js
https://react-select.com/
MIT License
27.49k stars 4.12k forks source link

AsyncSelect: defaultOptions should use current input value on first call #5714

Open mcintyre94 opened 1 year ago

mcintyre94 commented 1 year ago

When using <AsyncSelect> we can have the options loaded by calling loadOptions when the input is first opened by setting defaultOptions to true.

But on that first open the inputValue doesn't seem to be getting passed to the loadOptions call. This means that if the user was typing in the input, and we've saved their partial input, when they re-focus the input the options presented don't match their input.

Example codesandbox: https://codesandbox.io/s/codesandboxer-example-forked-mwmy98

Example video: https://github.com/JedWatson/react-select/assets/1711350/6b7b12df-cce9-4b9c-978c-21dbf82f7082

Here I type "re" and the filtered options are loaded correctly. I blur the input, leaving "re" as the input value. When I re-focus it, the options presented are the defaults before I typed anything, not those I had for the "re" input previously.

I think that defaultOptions: true should be calling loadOptions with the current value of inputValue every time the input is re-selected, so that the user is presented with the valid options for their current input.

mcintyre94 commented 1 year ago

If anyone else has this issue, as a workaround you can set onFocus to call onInputChange using a ref. Example: https://codesandbox.io/s/codesandboxer-example-workaround-8sqwt3?file=/example.tsx

    <AsyncSelect
      cacheOptions
      defaultOptions
      loadOptions={promiseOptions}
      inputValue={search}
      onInputChange={onInputChange}
      ref={(ref) => (selectRef.current = ref)} // const selectRef = useRef<Select | null>(null);
      onFocus={() =>
        selectRef?.current?.onInputChange(search, {
          prevInputValue: "",
          action: "set-value"
        })
      }
    />