I’m trying Svelte 5 for the first time today.
This is a reproduction of this issue.
As you can see if I select a date from the picker the {value}
is not assigned and the same if I press the “Clear” button.
Why?
Relevant code
<script lang="ts">
type Props = {
value?: Date | null;
id?: string;
onchange?: (e: Date | undefined) => void;
};
let {
value = $bindable(),
id,
onchange,
}: Props = $props();
$effect(() => {
console.log('value in $effect:', value);
});
$inspect(value);
const format = (date: typeof value): string => {
if (!date) return '';
if (date instanceof Date && isNaN(date.getTime())) return '';
return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, -8);
};
function handleOnChange(e: Event) {
const dateValue = new Date((e.target as HTMLInputElement).value);
console.log('handleOnChange:', dateValue);
value = dateValue;
if (onchange) onchange(dateValue);
}
function handleClear() {
console.log('handleClear :');
value = undefined;
if (onchange) onchange(value);
(document.getElementById(id) as HTMLInputElement).value = '';
}
</script>
<div>
{value}
<button type="button" onclick={handleClear}>Clear</button>
<input
type="datetime-local"
{id}
value={format(value)}
onchange={handleOnChange}
/>
</div>