I have these data in which the cat
will be the options
of the select
. However, as you can see in the sample data, there are 2 products with the same cat
which is the S-XL
. The problem here is that there will be 2 S-XL
that show up as the options
.
It shows up like this:
This is the data
:
const products = [
{
prodName: "Tumbler",
cat: "ML",
price: 1.5,
size: "500",
colorMap: { Black: 20, Pink: 10, Green: 5 },
id: "aRLMZkiSU7T0lcsPCSsV"
},
{
prodName: "Shirt",
cat: "S-XL",
price: 2.0,
size: "L",
colorMap: { Blue: 10, Black: 10 },
id: "uTHIR6OQFRuqP9Drft0e"
},
{
prodName: "Shirt2",
cat: "S-XL",
price: 1.0,
size: "M",
colorMap: { Blue: 10, Black: 10 },
id: "uTHIR6OQFRuqP9Drft0e"
},
{
size: "200",
cat: "CM",
price: 2.0,
colorMap: { Green: 50, Red: 19, Black: 20 },
prodName: "Notebook",
id: "y9ECyZBKp2OBekmWym4M"
}
];
How do I prevent or remove these duplicates?
Codesandbox link: https://codesandbox.io/s/react-hook-form-wizard-form-from-reddit-with-data-changed-the-autocomplete-with-select-cd1e6u?file=/src/fieldArray.js:995-3536
const FieldArray = ({ control, register, setValue, getValues }) => {
console.log(fields, "fields");
const selectedCategory = fields.map((object) => object.category);
console.log(selectedCategory, "selectedCategory");
const filtered = products.filter((d) => d.cat === `${selectedCategory}`);
console.log(filtered, "filter");
const sizes = fields.map((object) => object.size);
console.log(sizes, "size");
return (
<div>
<ul>
{fields.map((item, index) => {
return (
<li key={item.id}>
<FormControl>
<Controller
control={control}
name={`order.${index}.category`}
rules={{ required: "Please make a selection." }}
render={({ field, fieldState }) => (
<Select {...field}>
{products.map((option, i) => (
<MenuItem value={option.cat} key={i}>
{option.cat}
</MenuItem>
))}
</Select>
)}
/>
</FormControl>
<FormControl>
<Controller
control={control}
name={`order.${index}.size`}
rules={{ required: "Please make a selection." }}
render={({ field, fieldState }) => (
<Select {...field}>
{filtered.map((option, i) => (
<MenuItem value={option.size} key={i}>
{option.size}
</MenuItem>
))}
</Select>
)}
/>
</FormControl>
</li>
);
})}
</ul>
</div>
);
};
export default FieldArray;