Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inaccurate code example in docs #13160

Closed
henrykrinkle01 opened this issue Dec 15, 2024 · 0 comments · Fixed by #13161
Closed

Inaccurate code example in docs #13160

henrykrinkle01 opened this issue Dec 15, 2024 · 0 comments · Fixed by #13161

Comments

@henrykrinkle01
Copy link
Contributor

henrykrinkle01 commented Dec 15, 2024

Describe the bug

Today I come across this page:
https://svelte.dev/docs/kit/state-management#Component-and-page-state-is-preserved

...then navigating from /blog/my-short-post to /blog/my-long-post won’t cause the layout, page and any other components within to be destroyed and recreated. Instead the data prop (and by extension data.title and data.content) will update (as it would with any other Svelte component) and, because the code isn’t rerunning, lifecycle methods like onMount and onDestroy won’t rerun and estimatedReadingTime won’t be recalculated.
Instead, we need to make the value reactive:

<script lang="ts">
	import type { PageData } from './$types';

	let { data }: { data: PageData } = $props();

	let wordCount = $state(data.content.split(' ').length);
	let estimatedReadingTime = $derived(wordCount / 250);
</script>

However, this doesn't work at all. The line let wordCount = $state(data.content.split(' ').length); only runs once and won't re-run when navigating from /blog/my-short-post to /blog/my-long-post.
Assuming the blog page is for reading and not editing, it should be:

-	let wordCount = $state(data.content.split(' ').length);
+	let wordCount = $derived(data.content.split(' ').length);

This question arises almost everyday in the Discord server when someone declares something with $state which takes initial value from data they're surprised and it doesn't work when data is invalidated. Usually they also want to edit it but that's another issue.
PR opened.

Reproduction

N/A

Logs

No response

System Info

N/A

Severity

serious, but I can work around it

Additional Information

No response

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant