Manage Reactive Arrays in Svelte

When creating pages in the software framework and language Svelte, using reactive statements is really important. They allow you to tell Svelte to watch certain variables for changes and re-render any components using those variables. Creating arrays as reactive statements is a great way to manage lists on the front end and keep them up-to-date. However, this can be challenging with Svelte, I’ve recently discovered.

Problem 1: Typing the Array

If you’re using Typescript, you will quickly realize you can’t type a reactive statement. You can, however, type a normal array and then set the reactive statement to that typed array like so:

type Car = { id: number; make: string; model: string };
let cars: Car[] = [{ id: 1, make: "Honda", model: "Pilot" }, { id: 2, make: "Toyota", model: "Camry" }];
$: cars = cars; // or even simpler: just '$: cars;'

Problem 2: Updating the Array

This part really tripped me up. In Svelt, you need to create a new array and reassign it to the reactive declaration each time you update it.

Let’s say you have the same reactive array as above and want to add a new item to it. This won’t cause the array to update and re-render any components using the array:

cars.push({ id: 3, make: "Honda", model: "Civic" });

You must redeclare the array if you want it to update, like so:

cars = cars.push({ id: 3, make: "Honda", model: "Civic" });

Problem 3: Iterating on the Array

If you’re iterating over an array and creating components, you might notice a problem. When you update your array (using the method above), your components still might not re-render properly. This is probably because you aren’t telling Svelte that each component in that array is unique. Using Svelte’s key functionality will force Svelte to view each list item as unique. This will make Svelte destroy and recreate each component in the list that has changed.

You can achieve that solution like so:

{#each cars as car, i}
{#key car.id}
<Car make={car.make} model={car.model} />
{/key}
{/each}


I hope these findings help you out on your Svelte project! Feel free to leave any questions or comments for me.

Conversation

Join the conversation

Your email address will not be published. Required fields are marked *