by mvolkmann · 7y ago · 0 comments
My point is that Svelte stores are tedious and ironically seem to go against Svelte's filosophy of lean code.
Here are the docs if anyone wants to take a look:
https://github.com/sveltejs/rfcs/blob/master/text/0002-react...
<script> import {writable} from 'svelte/store'; const person = writable({name: 'Mark', zip: 63304});
function handleChange(event) {
const name = event.target.value;
person.set({...$person, name});
}
</script><input on:input={handleChange} value={$person.name} />
<div> Hello, {$person.name} at {$person.zip}! </div>
Of course if person is only used inside this component, you would not use a store. If it is used in other components, you would typically define and export the store in another .js file and import it everywhere it is needed.
My point is that this is a very simple way to share state between components and nowhere near as complex as the page you shared might indicate. That's because you do not need to use derived stores or custom stores. The simple writable store works in most cases.
Also, this works with pojos and primitive values. What happens when you add class instances, relationships, children, etc?
For example in a project I was working I had geometrical figures in my reactive data model. With classes I could simply do:
rectangle.getArea()
With MobX this was super simple to implement. If I wanted to change the position of the rectangle I would simply modify the x and y observable properties.The key is that when you update a Svelte store you must return a new value. It's enough to just return the value you updated. You see that happening here on lines 16 and 21.
I take your point that this is not as transparent as when using observables. But at least you can use classes that have relationships and call methods that modify the objects when those objects are in Svelte stores.
import { writable } from 'svelte/store';
export default function(state) { const { subscribe, set, update } = writable(state);
return {
subscribe,
getArea() { ... }
};
};