Skip to content

Commit 8624b08

Browse files
committed
fix(Select): Only dispatch populated event when appropriate
This fixes a problem where, when the Select's value is changed (by the user), the `change` and `populated` events are both dispatched, even if the list of options is unchanged. Those subsequent dispatches of the `populated` event make it too easy for consumers of this component to accidentally set the value of the Select back to what it was an instant before, effectively preventing the user's choice from "sticking" sometimes.
1 parent cda03de commit 8624b08

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

components/mdc/Select/Select.svelte

+8-2
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,17 @@ const selectedTextID = generateRandomID('select-selected-text-')
2121
2222
let element = {}
2323
let mdcSelect = {}
24+
let previousOptionsIDsCSV = ''
2425
2526
$: selectedIndex = options.findIndex((option) => option.id === selectedID)
2627
$: dispatch('change', options[selectedIndex] || {})
2728
$: mdcSelect.disabled = disabled
2829
$: if (options && mdcSelect.layoutOptions) mdcSelect.layoutOptions()
2930
31+
const getIDsCSV = (options) => options.map(option => option.id).join(',')
32+
33+
const optionsHaveChanged = (options) => previousOptionsIDsCSV !== getIDsCSV(options)
34+
3035
const recordSelectedID = (event) => (selectedID = event.detail.value)
3136
3237
const isOptionSelected = (option) => option.id === selectedID
@@ -43,10 +48,11 @@ afterUpdate(() => {
4348
// This makes sure the index is updated AFTER the select list contains the full list of options.
4449
mdcSelect.selectedIndex = selectedIndex
4550
46-
// If options have been provided, give the current processes time to finish
51+
// If options have been provided or changed, give the current processes time to finish
4752
// what they're doing, then indicate that this Select is now populated with
4853
// options. At this point, it's safe for the selectedID to be initialized.
49-
if (options.length > 0) {
54+
if (options.length > 0 && optionsHaveChanged(options)) {
55+
previousOptionsIDsCSV = getIDsCSV(options)
5056
setTimeout(() => {
5157
dispatch('populated')
5258
})

0 commit comments

Comments
 (0)