Scenario: In the process of building eCommerce software using react. For the product detail page, some products will have options (size, color) and some will not. The ones that do i iterate through the options and dynamically create select elements(code below):
<div className='mt-4'>
{item.options.length > 0
? item.options.map((option) => (
<div>
<p>{option.name}</p>
<select className='rounded-md border-2 w-32 h-12' onChange={handleAddOptions}>
{option.values.map((val) => (
<option value={val}>{val}</option>
))}
</select>
</div>
))
: ''}
</div>
Here is the handleAddOptions function:
const handleAddOptions = (e) => {
setOptions([...options, e.target.value]);
};
Now this works but not the way I want it to. It just keeps adding the options to one big array. I need the array to only be one option from each selection, no matter if the user changes multiple times.
Example:
Options are Size and Color (There could always be more though)
User picks small and blue then switches size to medium. My code would create an options array like this: [small, blue, medium] which would hold two size selections(can't have that).
EDIT: The final options array should only ever have one option from each selection. so in this case, if the user selects size many times the final array should only hold the most recent size option.