Consider that I have some array of objects, from which things may be added and removed. For each object, I want a Svelte component rendered.
If an object is removed, I want its corresponding Svelte component to be destroyed. If an object is added, I want a corresponding Svelte component to be created.
So far I have something naive, like this:
<script>
let someObjects = [];
const addObject = (obj) => {
someObjects = [...someObjects, obj];
}
const removeObject = (idx) => {
someObjects.splice(idx, 1);
someObjects = someObjects;
}
// ...
</script>
{#each someObjects as obj}
<SomeComponent object={obj} />
{/each}
This doesn't quite work. If you remove an object partway through the array, then in fact, from Svelte's perspective, the final element of the array has been removed, and other elements have just been modified.
This means that Svelte components are retained but with changed object parameters, which breaks any internal state and what-have-you.
How can I force an object halfway through the array to be destroyed, and keep the others from changing? Is the solution perhaps related to bind:this?
This can be filed away under "read the docs" (thanks Corrl).
Simply ensure your object has some kind of unique identifier as a field, say id, then use a keyed each block:
{#each someObjects as obj (obj.id)}
<SomeComponent object={obj} />
{/each}