Async React Select component how to change the argument of the loadOptions function

2.2k Views Asked by At

I have a react async select component. This component has a loadOptions props, where you need to pass a function to load data. At the moment it looks like this

const MyComponent = () => {
  const [positionId, setPositionId] = useEffect('');

  return (
    {
      positionId &&
      <AsyncSelect
        loadOptions={(search, prevOptions, additional) => loadMyOptions(search, prevOptions, additional, positionId)}
          (...other props)
        />
    }

      <Input
      value={positionId}
      onChange={(e) => setPositionId(e.target.value)}
      />
  )
}

The loadMyOptions function describes the data loading logic. This function takes the last parameter, positionId, which changes depending on what was entered in the input field. Now if you enter a value in the input field, then AsyncSelect appears and it loads the necessary options. But if after that you enter something else in input and change the positionId, and try to load new data into AsyncSelect, then it doesn't send a request to the backend with the new positionId value.

I tried to wrap the function in useCallback

const loadNewOptions = useCallback(
  (search, prevOptions, additional) => {
    return loadMyOptions(search, prevOptions, additional, positionId);
  },
  [positionId]
);

But it did not help. Please tell me how to make it so that when changing positionId and clicking on AsyncSelect, a request with a new value of positionId goes to the backend?

1

There are 1 best solutions below

3
I am L On

It seems that there's a race condition somewhere in your code, but you don't have to use the "outer" positionId, instead use the one that you pass instead:

    const loadNewOptions = useCallback((search, prevOptions, additional, posId) => {
      return loadMyOptions(search, prevOptions, additional, posId)
    }, [])