How to Combine Stores Together in Svelte
In Svelte, you can use a derived store, if you want a store to have a value based on other stores. This way, you can combine multiple stores together.
Copied to clipboard!
<script>
import { writable, get, derived } from 'svelte/store'
const vegetables = writable(['π₯', 'π₯', 'π₯']);
const fruits = writable(['π₯', 'π', 'π
']);
const derivedFood = derived([vegetables, fruits], ($values, set) => {
set([...$values[0], ...$values[1]]);
});
const set = () => fruits.set(get(fruits).concat(βπβ))
// fruits has changed but this will still log out
// [βπ₯β, βπ₯β, βπ₯β, βπ₯β, βπβ, βπ
β, βπβ]
derivedFood.subscribe(value => console.log(value));
</script>
<button on:click={set}>Add fruit</button>
When one of the store's value changes, the derive store can be notified through a subscribe method.
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews