sveltejs / svelte

Cybernetically enhanced web apps
https://svelte.dev
MIT License
78.44k stars 4.11k forks source link

`state_reference_locally` warning message is unclear #13079

Open sacrosanctic opened 3 weeks ago

sacrosanctic commented 3 weeks ago

Describe the bug

https://github.com/sveltejs/svelte/blob/0203eb319b5d86138236158e3ae6ecf29e26864c/packages/svelte/src/compiler/warnings.js#L642-L648

"How to use a closure?" was asked several times in discord. In addition, closure only refers to functions where classes also serve the same purpose.

I propose an update to the message "State referenced in its own scope will never update. Did you mean to reference it inside either a function or a class?"

related discord posts https://discord.com/channels/457912077277855764/1235970955612786719 https://discord.com/channels/457912077277855764/1278658234810634282 https://discord.com/channels/457912077277855764/1275188058089586688

Reproduction

.

Logs

No response

System Info

.

Severity

annoyance

dummdidumm commented 3 weeks ago

Another idea

State referenced in its own scope will never update. If you want to keep reactivity alive across boundaries, use a closure (like an arrow function, e.g. foo(() => myState) instead of foo(myState))

brunnerh commented 3 weeks ago

The first sentence could maybe also be simplified, the reference to scope does not seem all that helpful and it might be more straightforward to tell the user what will happen rather that what won't. E.g. something like

This state is only read once.

sacrosanctic commented 3 weeks ago

I imagine this situation would be quite common and will be mentioned in the upcoming docs.

This state is only read once. If you want reactivity, use a closure (like an arrow function, e.g. foo(() => myState) instead of foo(myState)). See https://docs...