Cookie
Cookie

Reputation: 434

Dynamically get/set store value in svelte from input

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".

Upvotes: 3

Views: 1811

Answers (1)

brunnerh
brunnerh

Reputation: 184376

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.

Upvotes: 3

Related Questions