Search code examples
sveltekit

How to refresh state when opening the same route


I have a top menu bar with links to the different pages on my website. When somebody is on one of those pages and makes some state changes (like filling in a form), then I kind of expect the page to reset to its initial state when the user clicks on the same menu link again. But instead nothing really happens, the state doesn't reset.

As an example, just imagine a simple counter page.

<script>
let count=0;
</script>

count: {count}
<button on:click={() => (count += 1)}>+</button>

If I go from Page A to Counter Page, press the + button, then press the link to Counter Page again, the count will still be 1. But if I go from Page A to Counter Page, press the + button, then go back to Page A and then back to Counter Page, the state has been reset and the count is 0 again, as SvelteKit sees this as a route changes.

I want that state reset to happen even if the route stays the same. How can I make this happen?


Solution

  • You could e.g. use something like the onNavigate hook to reset state; it fires on navigation to the same route as well.

    (There are also beforeNavigate and afterNavigate hooks.)