Svelte add param to derived state and keep its reactivity

Viewed 291

In this example, $derivedValue is reactive; if myArray is changed at index 3, it will change automatically, too.

App.svelte

<script>
    import { myArray, derivedValue } from './store';
</script>

<h1>{$myArray}</h1>
<h1>{$derivedValue}</h1>

store.js

import {derived, writable} from 'svelte/store';

export const myArray = writable([6, 7, 8, 9, 10]);
export const derivedValue = derived(myArray, value => value[3]);

I would like to create a reactive getter, which looks like this:

export const derivedValue = index => derived(myArray, value => value[index]);

Of course, in this case derivedValue is a function and is not subscribable anymore. Is there a way to create such a subscribable reactive derived value with a parameter?

1 Answers

derivedValue will indeed be a function, but it returns a store. You would use it like this:

<script>
    import { myArray, derivedValue } from './store';
    const first = derivedValue(0);
</script>

<h1>{$myArray}</h1>
<h1>{$first}</h1>

If you want this index to be reactive as well, you could reactively generate the store:

$: current = derivedValue(index)

and still use it as a regular store: $current

Related