1

How to simplify $: code?:

Symbol.svelte

<script>
    export let symbol;
    $:c = symbol.c;
    $:name = symbol.name;
    $:{console.log("log Symbol", name, c)}
</script>
<div on:click={()=>symbol.c=0} >
    {name} {c}
</div>

I dream of something like:

export let symbol;
$:{c,name} = symbol;

I can't use...

export let c,name;

...because in on:click I have to modify the symbol object with symbol.c = 0 - without this my store named list will not update.

The whole example: https://svelte.dev/repl/37e3a1fa96fc4f1dbc7cfcafb1edc439?version=3.22.1

PS, If you can use export let c, name; without losing the store update, please specify how to do it.

lukaszpolowczyk
  • 605
  • 1
  • 7
  • 27

2 Answers2

2

If you want to destructure a variable in a reactive statement, simply wrap the statement in parentheses:

$: ({ c, name } = symbol);

Learn more here: object destructuring without var

1

As it stands now, you're currently not updating your list store in your on:click handler. In fact, you have no method to set/update your list store other than to initialize it or set an element to zero using an odd mechanism that relies on another store.

I honestly cannot make much sense of your store, but nonetheless, using the store as you have designed it and piggybacking on its existing methods, the following will work and actually update your store:

Symbol.svelte

<script>
  import { list, inputSymbol } from './stores.js';
  export let c, name
  $:console.log("log Symbol", name, c)
</script>
<div on:click={() => {
  inputSymbol.set(name)
  list.setToZero()
}}>
  {name} {c}
</div>

App.svelte

...
{#each $list as symbol (symbol.name)}
    <Symbol {...symbol}/>
{/each}

See REPL (added list store console log in App.svelte to actually track store updates)

Thomas Hennes
  • 9,023
  • 3
  • 27
  • 36