Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically get/set store value in svelte from input

Tags:

svelte

I want to do this, TLDR:

/** This is the Input.svelte */

<script>
  export let identifier;

  import * as state from "./store"
</script>

<input bind:value={$state[identifier]} />

Longer story, I've defined a load of input fields in a list of objects, which I then iterate over and put on the <Input field /> component... but I need to save these values in a store to then continuously update a "Preview panel".

like image 593
Cookie Avatar asked Feb 07 '26 22:02

Cookie


1 Answers

That works more or less as is. The only problem is the state import/export. If you import via * that object is not going to be a store, but you can just export a single store instead.

store.js

import { writable } from 'svelte/store';
export const state = writable({});

Input.svelte

<script>
  import { state } from "./store";
  export let identifier;
</script>
<input bind:value={$state[identifier]} />

Example usage:

<script>
    import Input from './Input.svelte';
    import { state } from './store';
</script>

<Input identifier="value1"/>
<Input identifier="value2"/>

<p>Value1: {$state.value1}</p>
<p>Value1: {$state.value2}</p>

REPL

The identifier could be set dynamically as well, e.g. in an each block.

REPL using each


PS: You might want to pass in the store as a property or use a context instead of a global import. That way it is more transparent where the state is coming from and where it is being used. It also makes testing components easier.

like image 75
H.B. Avatar answered Feb 12 '26 06:02

H.B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!