Svelte.js deriving stores of stores

Gustav Corpas
5 min readNov 9, 2023
Svelte.js

This article is about working with nested stores, or stores of stores, or reactive arrays of stores, or whatever you would want to call them. Basicly this:

const stores = writable([writable(0), writable(0)]);

Why would you want this? Weeell, that part is up to you.. But if you find yourself doing this, stop for a second and consider if you are over-complicating things or if you really need this. Maybe there is an easier way to set up things.

Super quickly about THE BEST FRAMEWORK ❤️

Svelte.js is a javascript framework, that I have fallen completely in love with, and I will allow myself to be super opinionated about it :). It is THE BEST framework, because it is super fast. It’s fast because it is clever about figuring out how reactive values depend on each other at compile time, rather than just updating everything all the time.

Svelte shifts as much work as possible out of the browser and into your build step. No more manual optimisations — just faster, more efficient apps. — svelte.dev

It’s kind off the “keep it simple, stupid” of javascript frameworks.

Super quickly about svelte stores

If you have never heard of svelte stores, chances are this article is not for you. Go use them, I’ll be here if you wanna come back some day! :)

Just to remind ourselves. A store is something that allow us to subscribe to data like this:

const number = writable(0);
number.subscribe(value => console.log(value)); // will log out 42.
number.set(42);

The “problem”

I have recently been working on a project that has a lot of reactive data (using a streaming database, that is why). Here I ended up with reactive arrays (or stores) that contained objects with stores. Example:

const animals = writable([new Animal(), new Animal()]);
/// ...
class Animal {
name = writable("Fido");
age = writable(14);
}

Say we wanted to create a derived store (a store based on other stores) that calculates the total age of all Animal classes in the animals store. We now have a problem because a derived store, needs to…

--

--

Gustav Corpas

I write about technology and society. Or anything that is interesting to me.