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
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: