Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Why does this code partially persist browser history?

$
0
0

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:

  1. when you first open it there are many lines in console and I don't know why

  2. 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?


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>