Svelte: Reactive statement not found when used inside regular function

Created on 18 Jun 2019  路  2Comments  路  Source: sveltejs/svelte

I've run into a situation, where a reactive statement, combined with .map(), is not found when used inside a regular function, but is found when used inside an arrow function:

const someOtherStuff = [1,2,3];

$: stuff = someOtherStuff;

function willFail() {
  stuff.map(i => i);
}

const willWork = () => {
  stuff.map(i => i);
}

When looking at the compiled output, it seems that the compiler hoists the regular function willFail outside of the instance function's scope - that's where the variable for the reactive statement $: stuff resides, and thus it becomes unreachable from the function willFail.

If the reactive statement is assigned on it's own line without chaining a .map, like so:

function willNOTFail() {
  const s = stuff;
  s.map(i => i);
}

...it works as expected and in the compiled output the willNOTFail function is now included inside the scope of instance.

Here is a reproduction in REPL: https://svelte.dev/repl/dde38fd1a7a24d5b84392f24fa933dc8?version=3.5.1


Stack trace

Uncaught ReferenceError: filteredHeros is not defined
at HTMLButtonElement.useFunctionAlert (eval at handle_message (about:srcdoc:13), :499:26)
useFunctionAlert @ VM741:499

bug

Most helpful comment

Fixed in 3.6.0, thanks

All 2 comments

Fixed in 3.6.0, thanks

Great!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Rich-Harris picture Rich-Harris  路  3Comments

robnagler picture robnagler  路  3Comments

AntoninBeaufort picture AntoninBeaufort  路  3Comments

rob-balfre picture rob-balfre  路  3Comments

bestguy picture bestguy  路  3Comments