'How to make if statement rerender component svelte
Here is what I have for my script :
function changeCart(subCat)
{
let addedCat = {id: subCat._id,name: subCat.name, name_categorie: subCat.name_categorie}
let exist = $cart.some(element => {
if(element.id === addedCat.id)
{
return true
}
})
if(exist)
{
$cart.some(element => {
if(element.id === addedCat.id)
{
$cart.splice($cart.indexOf(element, 1))
return true
}
})
}
else
{
$cart = [...$cart, addedCat]
}
console.log($cart)
}
and here is my html :
{#each subCategories as subCategories}
{#if ($cart.indexOf(subCategories.name) > -1)}
<div class="media ali list-group-item list-group-item-action clique selected" on:click={() => changeCart(subCategories)}>
<Management/>
<div class="media-body" >
<h4 class="media-heading">{subCategories.name}</h4>
</div>
</div>
{:else}
<div class="media ali list-group-item list-group-item-action clique" on:click={() => changeCart(subCategories)}>
<Management/>
<div class="media-body" >
<h4 class="media-heading">{subCategories.name}</h4>
</div>
</div>
{/if}
{/each}
I want to change this line :
{#if ($cart.indexOf(subCategories.name) > -1)}
The goal is to check if an object is already in $cart like the script part already do but I don't know how to make the modification for the if statement in my html
Solution 1:[1]
I found the solution : this is what I've done :
Script part :
function changeCart(subCat)
{
let addedCat = {id: subCat._id,name: subCat.name, name_categorie: subCat.name_categorie}
let exist = checkIfExist(subCat)
if(exist >= 0)
{
$cart = $cart.filter(item => item.id !== subCat._id)
}
else
{
$cart = [...$cart, addedCat]
}
console.log($cart)
}
function checkIfExist(cat)
{
for( let i = 0; i < $cart.length; i++)
{
if($cart[i].id == cat._id){
return i
}
}
return -1
}
and the html part :
{#key $cart}
{#each subCategories as subCategory}
<div class={`media ali list-group-item list-group-item-action ${checkIfExist(subCategory) >= 0 ? "selected" :""} clique`} on:click={() => {changeCart(subCategory)}}>
<Management/>
<div class="media-body">
<h4 class="media-heading">{subCategory.name}</h4>
</div>
</div>
{/each}
{/key}
Solution 2:[2]
You can simply use the class:<name> Svelte directive. To add better readability, you could also make use of the new-ish @const block directive:
{#each subCategories as subCategory}
{@const selected = $cart.some(element => element.id === subCategory.id)}
<div class:selected class="media ali list-group-item list-group-item-action clique" on:click={() => changeCart(subCategory)}>
<Management/>
<div class="media-body" >
<h4 class="media-heading">{subCategory.name}</h4>
</div>
</div>
{/each}
Note: also changed the name of the currently iterated value to subCategory (don't name the iterator the same as the iteratee).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LeMecWeird |
| Solution 2 | Thomas Hennes |
