0

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

1
  • It your backend supposed to accept and return duplicate values? Commented Apr 27, 2021 at 14:24

2 Answers 2

1

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>
))}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm afraid there is an error here. You cannot iterate Set with map, need to convert it to array with Array.from(set)
Thanks guys. The thing is the sourceData is already unique in value. I am guessing that the second option is the cause for the duplicate value: <option selected value={data.source._id}>{data.source.sourcename}</option>
So, I think the option outside the map is unnecessary. The options generated by the map should be sufficient. You can also remove this value from sourceData with the slide method: stackoverflow.com/questions/5767325/…
0

This solved the issue for me

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.