From b6575cc29daab783fa5d745c978fe65413be1eb5 Mon Sep 17 00:00:00 2001 From: Simon Holthausen Date: Fri, 10 May 2024 15:43:52 +0200 Subject: [PATCH] fix: don't warn on writes to `$state` fixes #10905 --- .changeset/calm-buses-clap.md | 5 +++++ packages/svelte/src/compiler/phases/2-analyze/index.js | 8 +++++++- .../validator/samples/static-state-reference/input.svelte | 5 +++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 .changeset/calm-buses-clap.md diff --git a/.changeset/calm-buses-clap.md b/.changeset/calm-buses-clap.md new file mode 100644 index 0000000000..409949443d --- /dev/null +++ b/.changeset/calm-buses-clap.md @@ -0,0 +1,5 @@ +--- +"svelte": patch +--- + +fix: don't warn on writes to `$state` diff --git a/packages/svelte/src/compiler/phases/2-analyze/index.js b/packages/svelte/src/compiler/phases/2-analyze/index.js index e4d6f6a4db..cf05dfbf53 100644 --- a/packages/svelte/src/compiler/phases/2-analyze/index.js +++ b/packages/svelte/src/compiler/phases/2-analyze/index.js @@ -1242,6 +1242,7 @@ const common_visitors = { if ( context.state.analysis.runes && node !== binding.node && + context.state.function_depth === binding.scope.function_depth && // If we have $state that can be proxied or frozen and isn't re-assigned, then that means // it's likely not using a primitive value and thus this warning isn't that helpful. ((binding.kind === 'state' && @@ -1252,7 +1253,12 @@ const common_visitors = { !should_proxy_or_freeze(binding.initial.arguments[0], context.state.scope)))) || binding.kind === 'frozen_state' || binding.kind === 'derived') && - context.state.function_depth === binding.scope.function_depth + // We're only concerned with reads here + parent.type !== 'AssignmentExpression' && + parent.type !== 'UpdateExpression' && + (parent.type !== 'MemberExpression' || + (context.path.at(-2)?.type !== 'AssignmentExpression' && + context.path.at(-2)?.type !== 'UpdateExpression')) ) { w.state_referenced_locally(node); } diff --git a/packages/svelte/tests/validator/samples/static-state-reference/input.svelte b/packages/svelte/tests/validator/samples/static-state-reference/input.svelte index 2971960a14..72590de4f4 100644 --- a/packages/svelte/tests/validator/samples/static-state-reference/input.svelte +++ b/packages/svelte/tests/validator/samples/static-state-reference/input.svelte @@ -6,6 +6,11 @@ console.log(obj); console.log(count); console.log(doubled); + // these are ok because they're writes + count++; + count = 1; + obj.a++; + obj.a = 1;