Skip to content

Lint when passing $state/$derived outside of Svelte context #1419

@KieranP

Description

@KieranP

Motivation

Reduce a series of bugs that result from 3rd party libs and browsers builtins like structuredClone from barfing when passing $state/$derived values, which are wrapped in a proxy.

See sveltejs/svelte#15345 (comment)

Description

Passing Svelte $state/$derived to methods that come from outside of Svelte context (i.e. not into components or functions from .svelte.ts files) is usually going to result in unexpected behaviour/bugs. Whats more, $state.snapshot is not usable outside of Svelte context, so it would be best to enforce that call before a variable is passed around.

Examples

<script>
import state from './state.svelte.ts'
import store from './store.ts'
import tooltip from 'bootstrap'

const { defaultState } = $props()
const initialState = structuredClone(defaultState)

<!--GOOD -->
state.set(defaultState) // state comes from a `.svelte.ts` file, so still within Svelte context

tooltip.set("Hello") // This is fine, because the string is not $state/$derived

<!--BAD -->
store.set(defaultState) // Not ok, because store.ts doesn't know how to handle $state/$derived and $state.snapshot won't be available inside it

tooltip.set(defaultState.title) // Not ok, because defaultState is deeply reactive and so title is a $state
</script>

Additional comments

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions