fix(select): use first SelectItem value as default if selected is undefined (#1353)

Fixes #570
This commit is contained in:
metonym 2022-06-18 10:13:42 -07:00 committed by GitHub
commit f8b1c8a23a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
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) => {