Skip to content

[Svelte 5] error mutating property of an object and setting the state that is containing it to null/undefined #10000

Closed
@hawk93

Description

@hawk93

Describe the bug

Given a $state that can be an object or undefined and a function that mutates the object and the state at the same time

<script lang="ts">
	let data = $state<{ num: number } | undefined>({ num: 1 });

	function expire() {
		data.num = data.num - 1;
		if (data.num <= 0) data = undefined;
	}
</script>

{#if data}
	<button {expire}>Click</button>
	
	<p>expires in {data.num} click</p>
{/if}

If you try to access an object property in the template you get an error in the console about reading property of null.

You can work around the problem using optional chaining data?.num but considering the property is accessed inside an if block I would expect to not need it

Reproduction

REPL

Logs

Error: Cannot read properties of undefined (reading 'num')

System Info

svelte 5.0.0-next.26

Severity

annoyance

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions