fix(select): default selected to first item value if undefined

Fixes #570
This commit is contained in:
Eric Liu 2022-06-18 05:47:56 -07:00
commit 262d2c33a1
2 changed files with 23 additions and 2 deletions

View file

@ -71,8 +71,26 @@
const dispatch = createEventDispatcher();
const selectedValue = writable(selected);
const defaultSelectId = writable(null);
const defaultValue = writable(null);
setContext("Select", { selectedValue });
setContext("Select", {
selectedValue,
setDefaultValue: (id, value) => {
/**
* Use the first `SelectItem` value as the
* default value if `selected` is `undefined`.
*/
if ($defaultValue === null) {
defaultSelectId.set(id);
defaultValue.set(value);
} else {
if ($defaultSelectId === id) {
selectedValue.set(value);
}
}
},
});
afterUpdate(() => {
selected = $selectedValue;
@ -80,7 +98,7 @@
});
$: errorId = `error-${id}`;
$: selectedValue.set(selected);
$: selectedValue.set(selected ?? $defaultValue);
</script>
<div class:bx--form-item="{true}" {...$$restProps}>

View file

@ -13,8 +13,11 @@
import { getContext, onMount } from "svelte";
const id = "ccs-" + Math.random().toString(36);
const ctx = getContext("Select") || getContext("TimePickerSelect");
$: ctx?.setDefaultValue?.(id, value);
let selected = false;
const unsubscribe = ctx.selectedValue.subscribe((currentValue) => {