Skip to content

In SelectMulti (& confirm in SelectSingle), determine currently selected options by *value*, rather than by *reference* #78

Open
@jackkoppa

Description

@jackkoppa

Currently, SelectMulti uses a simple indexOf to determine if a given option is currently selected.

It does this by checking "is this item from the options array, present in the current selectedOptions?"

See here: https://github.com/politico/vue-accessible-selects/blob/v0.12.0/src/SelectMulti.vue#L272

const optionIndex = this.selectedOptions.indexOf(option)

Or here: https://github.com/politico/vue-accessible-selects/blob/v0.12.0/src/SelectMulti.vue#L356

'option-selected': selectedOptions.indexOf(option) > -1,

This works fine for most cases: we expect that the options passed into the component will remain the same as when the component was initialized, and as such, it should be safe to compare by reference, as indexOf does, to see "is this specific object reference in the selected array"

A problem occurs, however, as soon as we start to have more complicated parent components, that might update the list of options passed into SelectMulti - perhaps based on an API call. Now, even though the original values of the options list may still exist, they now have a new reference. And thus, indexOf is no longer an accurate way to find these options & determine if they are in the selectedOptions array

Solution

Allow for "find by value", rather than "find by reference". i.e. let's choose a way to reliably compare the items in the options array, with those that have been added to the selectedOptions array. That does not rely on objects in each array having the same reference. Since the reference approach won't be terribly maintainable, and will quickly lead to the types of confusing bugs we've already begun to experience @ Politico.

In this issue, then, let's first write a failing test:
"When I update the options prop to be an array full of new references, selected options are still correctly displayed as long as they match the value of current selectedOptions"

Then, let's fix the code so the spec passes

Note: SelectSingle is already doing compare-by-value here, but let's make sure it has the appropriate specs & testing regardless

Metadata

Metadata

Assignees

Labels

bugSomething isn't workingenhancementNew feature or requesttestsImprove or add specs

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions