Reputation: 3
I debuted Svelte a while ago and started a project but am having some problem with components.
I have 2 arrays (boxes1 and boxes2) which contents are displayed in an each loop inside 2 different divs next to each other. We can add element to each array by clicking the add button : the left one for boxes1 and the right one for boxes2. Each elements from both arrays have an id starting from 1 and is reset to 1 every time all the elements from the array are removed. Each odd elements inside both divs are dynamic component base on a component with a red background. Each even elements inside both divs are dynamic component based on a component with a blue background. Each elements from both divs can be removed by clicking the button inside the element : by clicking the button, the component inside the element sends an event to the parent component so that the element is removed from the array before being destroyed.
Here's the problem : after adding some elements to one array then removing them all, and then adding elements again, the first element added doesn't show in the div but is present inside the array. Not resetting the id when all the elements have been removed solves the problem but I need it to be reset.
I can understand that my explanation is quite confusing so here's the REPL: https://svelte.dev/repl/ae13251cf3ac4c12ba10eabe20f376d1?version=3.44.0
Upvotes: 0
Views: 609
Reputation: 386
The problem is here on:destroy
you set show = false
, So when you remove the last element from the array show = false
that's why the first component is not shown. You can update your Box.svelte
component like this:
<script>
import { onMount, createEventDispatcher } from "svelte";
export let template;
export let templateProps;
let show = true;
const dispatch = createEventDispatcher();
$: if(templateProps && templateProps.heading == 0){
show = true;
}
const destroy = () => {
show = false;
dispatch("destroy");
};
</script>
{#if show}
<svelte:component
this={template}
on:close={() => destroy()}
{...templateProps}
/>
{/if}
Upvotes: 1