'why is my react-select component letting the user select the first selection again as a second selection?

This one's a little difficult to explain. Anyways, I'm using react-select in my React App, and I'm trying to keep track of all the selections that the user has made with it. There are multiple Creatable -components from react-select.

My issue is with the multi select dropdwns. Once I select the first selection for a multi choice dropdown, the second time I try to select, the first option is still in the list of selectable. After the first selection, the others can be selected normally and they disappear from the list once selected. Only the FIRST selection is causing this. Here's an image. Here's the code for the dropdown component:

<Creatable
          isValidNewOption={isMulti ? isWithinSelectionRange : undefined}
          components={isMulti ? { Menu } : undefined}
          isMulti={isMulti}
          options={options}
          styles={colorStyle}
          theme={colorTheme}
          placeholder={isMulti ? `Select up to ${selections}` : "Select"}
          onChange={(selections) =>
            updateSelections(
              selectionData,
              updateSelectionData,
              selections,
              uniqueId
            )
          }
        />

The issue seems to lie in the usage of the updateSelections -function in the onChange. Here's the code for the updateSelections:

export function updateSelections(
  selectionData: ISelection[],
  updateSelectionData: Function,
  selections: unknown,
  id: number
) {
  const typedSelections = selections as IOption[]
  const data = { id, selections: typedSelections }
  const existing = selectionData.find((x) => x.id === id)
  data.selections.sort((a, b) => a.value.orderId - b.value.orderId)

  if (existing === undefined) {
    updateSelectionData([...selectionData, data])
  } else {
    const copy = selectionData
    const index = copy.indexOf(existing)
    copy[index] = data
    updateSelectionData(copy)
  }
}

updateSelections is using a passed in function updateSelectionData (a bit confusing, renaming it later) which is actually just a function that updates state:

const updateSelectionData = (data: ISelection[]) => setSelectionData(data)

It does seem like the issue is caused by updating state. To confirm this, I changed the updateSelectionData to just console.log something random. by doing this (removing state updating) the dropdown works as it should. Here's an image of how it SHOULD work.

I really need to keep track of all the selections, and having this in the state makes sense, so what is causing this issue, and how do I fix it?

parent: https://www.toptal.com/developers/hastebin/anicawukob.js
child: https://www.toptal.com/developers/hastebin/awodurudow.js



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source