fullstacknoob
fullstacknoob

Reputation: 233

SvelteKit: How to populate HTML with content from new array after page has already been loaded?

I am displaying a list of JSON objects containing user chats. If the user types something into the searchbar, the matching JSON objects from the original chats list are being pushed into the new filtered_chats array. I didn't include this code logic since this is working and filtered_chats is being populated. (Note: filtered_chats starts out as an empty array in the script tag. Maybe this is helpful)

The problem I'm facing is that SvelteKit won't feed the new array to the HTML to show only the elements from filtered_chats instead of all of the chats from chats. It checks for the original array only and leaves the rendered contents as they already are.

Script:

<script lang="ts">
import ChatSidebarElement from "$components/ChatSidebarElement.svelte";

export let chats : JSON;

var filtered_chats = [];
var searchval = "";
function search() {
    // this pushes chat objects into "filtered_chats" if they match the search pattern
}

HTML:

<div class="mb-4">
    <input type="search" class="form-control text-dark" bind:value={searchval} on:input={search} placeholder="Search chats">
</div>
<h3 class="text-light">Open Chats</h3>
{#if chats.length > 0}
    <div class="chats">
        {#if filtered_chats.length > 0}
            <h1 class="text-light">{searchval}</h1>
            {#each filtered_chats as chat}
                <ChatSidebarElement chat={chat}></ChatSidebarElement>
            {/each}
        {:else}
            {#each chats as chat}
                <ChatSidebarElement chat={chat}></ChatSidebarElement>
            {/each}
        {/if}
    </div>
{:else}
    <li>
        <div class="info">
            <div>You don't have any open chats!</div>                                         
        </div>
    </li>
{/if}

Upvotes: 0

Views: 763

Answers (1)

Sazzad Ahmed
Sazzad Ahmed

Reputation: 266

Svelte only updates the UI when a variable is reassigned. With that in mind, if you mutate an array instead of reassigning it with a new state, it will not update the UI. For example:

<script>

let items = ['1', '2', '3']

// Wrong! UI won't be updated
items.push('4')

// Right! UI gets updated
items = [...items, '4']

// Or you can also do this
items = items.concat('4')

</script>

Upvotes: 1

Related Questions