Search code examples
sveltesveltekit

Can I prevent HTML input (checkbox, text, etc.) from resetting upon view change?


I have a simple Svelte app with two basic routes. On the main page, I have a textbox. When I switch between routes, the value of the textbox resets.

Is there a way to avoid this?


Solution

  • This can be solved with more than one mechanism, and I don't pretend to cover all of them. Instead, I'll explain why this happens and give you one example of how it can be solved.

    Cause of the Problem

    I am assuming that this textbox is in the +page.svelte file located in the routes folder. When you navigate to another page, this page component gets unloaded. That is: Removed from the DOM. The objects are destroyed and the associated class is also destroyed. This destroys any collected user input.

    Solving it with a Store

    The most straightforward way of solving this would be to create a Svelte store that persists the input box's value.

    Create a src/stores folder, and add the file homepage.js with this content:

    import { writable } from 'svelte/store';
    
    export default writable(undefined);
    

    Just like that, you now have an object capable of persisting your homepage data.

    In your homepage's +page.svelte file:

    <script>
      import homepage from '../stores/homepage.js';
    </script>
    
    <h1>Homepage</h1>
    
    <input type="text" bind:value={$homepage} />
    

    By binding the textbox's value to the store, anything typed in the textbox will be preserved in the store.

    Now every time the homepage is visited, the input box will be in sync with the value of the store.