Nat
Nat

Reputation: 749

Select option duplicate values reactjs

I am getting duplicate values from the select option in an edit form. For example, in the select option, I have A and B, and let say I have in the database recorded as B. So when I go into the edit form I should see B being selected which working fine so far. But I see A, B, B instead of A and B.

I am not sure how do I get rid of the duplicate values. Here is the code:

  <div className="col-sm-10">
           <select id="sourcename" className="form-control" name="source" onChange={handleChange}>
                 {sourceData.map(option => (
                      <option value={option._id}>{option.sourcename}</option>
                      ))}
                      <option selected value={data.source._id}>{data.source.sourcename}</option>
          </select>
       </div>

Many thanks in advance and greatly appreciate any helps. Thanks

Upvotes: 0

Views: 959

Answers (2)

Nat
Nat

Reputation: 749

This solved the issue for me

<option value={option.value} selected={optionsState == option.value}>{option.label}</option>

Upvotes: 0

Bart Krakowski
Bart Krakowski

Reputation: 1670

You can simply use the Set: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

const uniqueData = new Set(sourceData)
[...uniqueData].map(option => (
  <option value={option._id}>{option.sourcename}</option>
))}

Upvotes: 1

Related Questions