Update a custom store object
There's lots of ways you can update a store dynamically from an input, including directly or indirectly via a function.
Given a simple writeable store...
stores.js:
import {writable} from "svelte/store";
export const writableStore = writable({
a: true,
b: true
});
... here's two examples of updating the values, directly (a) or indirectly (b):
App.svelte:
<script>
import {writableStore} from "./stores.js";
let b = $writableStore.b;
// This function could be on a "custom" store.
function updateB( value ) {
// Validate value in context of other values?
// Send to API.
// Result good ... update store.
$writableStore.b = value;
return $writableStore.b;
}
$: bCurrent = updateB( b );
</script>
<h2>A: {$writableStore.a}</h2>
<label for="a">Toggle A</label>
<input type="checkbox" id="a" bind:checked={$writableStore.a} />
<h2>B: {bCurrent}</h2>
<label for="b">Toggle B</label>
<input type="checkbox" id="b" bind:checked={b} />
REPL: https://svelte.dev/repl/fb09138522d84e7e9fbb642193e8258c?version=3.45.0
The example for b
waits to update the store, which may not be what you want.
If you can send to API via a "Save" button, then the example for a
may be all you need, calling a function via the button to send the store data to the API etc.
These are just super simple examples, I tend to use functions on custom stores for saving to the API etc and using the store's update()
function to sync results.