You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
...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:
<scriptlang="ts">importtype{PageData}from'./$types';
let { data }: {data: PageData}=$props();letwordCount=$state(data.content.split(' ').length);letestimatedReadingTime=$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
The text was updated successfully, but these errors were encountered:
Describe the bug
Today I come across this page:
https://svelte.dev/docs/kit/state-management#Component-and-page-state-is-preserved
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:
This question arises almost everyday in the Discord server when someone declares something with
$state
which takes initial value fromdata
they're surprised and it doesn't work whendata
is invalidated. Usually they also want to edit it but that's another issue.PR opened.
Reproduction
N/A
Logs
No response
System Info
Severity
serious, but I can work around it
Additional Information
No response
The text was updated successfully, but these errors were encountered: