DEV Community

Addie B
Addie B

Posted on

Svelte: derived stores based on an arbitrary array of stores

Say you have an array of stores, the length of which is not necessarily known. You want to create a derived store that updates its value when any of these array values changes. The derived store syntax is a bit obtuse on how this can be done, but it is possible. Here's an example:

import { writable } from "svelte/store"

const storeArray = [writable(1), writable(1), writable(1)]

const derivedStore = derived(storeArray, ([...arr]) => {
  // Do stuff with your array of stores
  // e.g., this code will set the derived store's value to true whenever all the stores are greater than 10:
  return arr.every(item => item > 10);
});
Enter fullscreen mode Exit fullscreen mode

The ... spread syntax here allows any number of stores to be passed into the derived constructor's callback function.

A caveat - the derived store won't be notified if new items are added to the store array, or the array itself is redeclared. For that, you could consider making the array itself a store, and use set and update whenever you want to change it.

storeArray = writable(storeArray)
const derivedStore = derived(
  [storeArray, ...storeArray], 
  ([...arr]) => {
    // arr[0] is the array itself, and arr.slice(1) contains the contents
  }
);
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
luist1228 profile image
luist1228

Also I'm a bit confused with the second snippet you named both storeArray, Im trying to implement it so if it's not much to ask could you help with this

Collapse
 
luist1228 profile image
luist1228

OMG Thankiu I couldn't wrap my mind around this, the first snippet was just the right thing I was looking for