I'm trying to understand how to persist state in the page URL's searchParams
.
But I don't understand how to do it.
I'm using this code:
<script lang="ts"> import { afterNavigate, goto } from '$app/navigation'; let condition = $state({}); $effect(() => { console.log("$effect"); const url = new URL(window.location.toString()); url.searchParams.set('condition', JSON.stringify(condition)); goto(url, { replaceState: false, noScroll: true, keepFocus: true }); }); afterNavigate(() => { console.log('afterNavigate()'); const url = new URL(window.location.toString()); const conditionFromParams = url.searchParams.get('condition'); console.log('conditionFromParams:', conditionFromParams); if (conditionFromParams !== JSON.stringify(condition)) { console.log('different!'); condition = JSON.parse(conditionFromParams || '{}'); } });</script>Write something here:<br><br><input type="text" bind:value={condition.search} /><br><br>condition: {JSON.stringify(condition)}
This is a reproduction: https://stackblitz.com/edit/sveltejs-kit-template-default-kgnoad.
But if you run it you'll see that:
when you first open it there are many lines in console and I don't know why
if I write in the text input the word "
hello
" and I go back with the browser back button the first time it brings me to "hell", if I click again it brings me to "" (nothing)
Why?