user15167046
user15167046

Reputation: 1

Svelte: Using reactive input in <script>

I am looking to use a reactive value to filter an array used in a chart. I tried both a bind:value and on:change approach. Both succeeded in outputting the index needed, but I am trying to use that value upstream in the <script> because there is a lot of processing of that data once the correct array index is selected.

Is there any way to use a reactive value in the script?

<script>
    let arrayIndex = 1; 
    let data_1 = { count: "a" };
    let data_2 = { count: "b" };

    let data_agg = [data_1, data_2];
    let data_filter = data_agg[arrayIndex];
</script>

<h1>Filter</h1>
<select bind:value={arrayIndex}>
    <option value={0}>0</option>
    <option value={1}>1</option>
</select>

<h1>Array Index</h1>
{arrayIndex}

<h1>Filtered Data</h1>
{Object.values(data_filter)}

REPL

Changing the value below "Filtered Data" is basically what I'm trying to achieve.

Upvotes: 0

Views: 315

Answers (1)

brunnerh
brunnerh

Reputation: 185117

Just replace let/const declarations with $: to make them reactive, in this case:

$: data_filter = data_agg[arrayIndex]

This makes sure that the value is updated if either data_agg or arrayIndex is changed.

Top level values depending on reactive values should also be reactive, e.g.

$: data_filter = data_agg[arrayIndex];
$: data_mapped = data_filter.map(x => ...);

If only the end result is needed in e.g. the HTML template or event handlers, reactive statements can be combined into blocks or functions. For the above example this could be done:

$: data_mapped = (() => {
  const data_filter = data_agg[arrayIndex];
  return data_filter.map(x => ...);
})();

Upvotes: 1

Related Questions