Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent User from creating duplicate values using React-Select Creatable?

I am using react-select' Creatable to make a dropdown and allow user to create new item to the list.

This is what I have:

<Creatable
  name="form-field-name"
  value={this.props.selectWorker}
  options={this.props.selectWorkers}
  onChange={this.props.handleSelectWorker}
/>

Right now user can create new name even though it already exist, creating duplicates like shown below.

Duplicate name

I saw that there is an option called isOptionUnique on react-select site.

Searches for any matching option within the set of options. This function prevents duplicate options from being created. By default this is a basic, case-sensitive comparison of label and value. Expected signature: ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean

I have not been able to use it. I have tried isOptionUnique=true, isOptionUnique={options:this.props.workers}, but I got Creatable.js:173 Uncaught TypeError: isOptionUnique is not a function error.

I can't find an example for isOptionUnique, what is the best way to filter react-select to prevent duplicates using Creatable?

like image 885
Iggy Avatar asked May 09 '17 18:05

Iggy


2 Answers

It's expecting a function

isOptionUnique(prop) {
  const { option, options, valueKey, labelKey } = prop;
  return !options.find(opt => option[valueKey] === opt[valueKey])
}

Don't forget to add it to your component instance

isOptionUnique={this.isOptionUnique}
like image 140
Shanimal Avatar answered Oct 12 '22 01:10

Shanimal


This can also be achieved using the isValidNewOption prop.

isValidNewOption = (inputValue, selectValue, selectOptions) => {
    if (
      inputValue.trim().length === 0 ||
      selectOptions.find(option => option.email === inputValue)
    ) {
      return false;
    }
    return true;
  }

you define a function taking three parameter of the inputValue you typed in, the selectValue if a value is selected and the existing options as selectOptions. The function should return true or false dependent on what conditions you want a new option to be valid. this will prevent addition of duplicates.

In the case above we prevent adding of new options if there is no text or if the email already exists in the available options

like image 2
Ianoti Avatar answered Oct 12 '22 00:10

Ianoti