svelte: select option with default selection.... broken in 3.42?
Describe the bug
This looks to work in 3.41 and before but breaks at 3.42 or newer. Docs don’t mention it at all so it is hard to trouble shoot.
Reproduction
Run this code.
<script>
let options = [
{ id: "4", value: "2019" },
{ id: "3", value: "2018" },
{ id: "2", value: "2017" },
{ id: "1", value: "2016" },
];
let selected = { id: "2", value: "2018" };
</script>
<select bind:value={selected}>
{#each options as option}
<option value={option} selected={selected.id === option.id}>{option.value}</option>
{/each}
</select>
<p>
Selected {JSON.stringify(selected)}
</p>
Logs
No response
System Info
Version 3.42 or newer
Severity
annoyance
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 20 (13 by maintainers)
This is expected behavior, IMO. It works fine to bind to an object, but the
selectedvariable needs to be a reference to the desired value (rather than a different object copy) so that strict equality comparison will work. Example: https://svelte.dev/repl/4601f621ce364685b1baee2d7b5c21a4?version=3.44.2Basically this line:
should be replaced with:
I’m not sure about your specific use-case. But at least your REPL can be fixed as this REPL.
You use property of object for
bind:value. Therefore it was updated by Svelte when selected option is changed. I meanoptions[0].nameis changed when selected option is changed. This is not Svelte bug. I think this is one of the common programming mistakes.IMO, in general, it would be better to use the
on:changeevent handler and use primitive types for thevalueattribute in such cases.Nevertheless, I think it would be useful to have object type support. For instance, Vue.js has such feature. (REPL)
@RaiVaibhav but I don’t want it to go back to the default one I want it to go to the correct one. I created a more real example of what I am trying to do here: https://svelte.dev/repl/e4698e605aca48d8937cb1ee32220835?version=3.44.2. With @baseballyama’s workaround, I can set additional properties of the object but in the case of an object that has 4+ properties, it isn’t that useful.
The code in the message wasn’t displaying correctly because it wasn’t wrapped in code blocks - I’ve just edited the original message.