Reputation: 4156
Why is the checkbox not working here?
I think Svelte is re-evaluating innerTeam
on change, but I don't understand why.
I'm changing innerTeam
not team
.
I'm using that reactive syntax to change innterTeam
only if team
changes! Not the other way!
REPL: https://svelte.dev/repl/1ef7657adbc545a0b595e2ab58069b4a?version=3.42.4
<script>
import {onMount} from "svelte";
import Inner from "./Inner.svelte"
let team = {
player: {id: "1", name: "John"},
full: false
}
onMount(() => setTimeout(()=> {
team = { player: {id: "2", name: "Bob"} }
}, 4000))
</script>
team: <pre>{JSON.stringify(team, null, 2)}</pre>
<Inner {team}></Inner>
<script>
export let team = undefined;
let innerTeam;
$: innerTeam = {
...team,
cars: []
}
function addCar() {
innerTeam.cars = [...innerTeam.cars, {id: "1", brand: "BMW"}]
}
</script>
<button on:click={addCar}>
Add car to customTeam
</button>
<br>
<input bind:checked={innerTeam.full} type="checkbox"/> Full?
<br>
customTeam: <pre>{JSON.stringify(innerTeam, null, 2)}</pre>
Upvotes: 1
Views: 381
Reputation: 8386
I'm using that reactive syntax to change innterTeam only if team changes! Not the other way!
Well not really. You're making a reactive declaration about innerTeam
so anytime that innerTeam
or team
changes innerTeam
will be updated. In your case innerTeam.full
is a value coming from team
and you're telling Svelte whenever innerTeam
changes reset innerTeam
equal to ...team, cars: []
you change full to true, Svelte changes it back like you told it to.
If you want the reactivity to be based around team
you can make a reactive statement about team
and have it call a function that updates innerTeam
:
let innerTeam
function updateInner() {
innerTeam = {
...team,
cars: []
}
}
$: team, updateInner()
However, doing it this way means when the team is updated any cars added will go away. Not sure if this is what you wanted or not, but it seems like what you described.
Here's a REPL showing the behavior, if you add cars and click the Increase ID# button the cars go away.
Upvotes: 2