0

In svelte I want to create a form with a Reset button. I use for that an object in a reactive variable that is initialised with an default object DEFAULT_OPTIONS:

<script>
    const DEFAULT_OPTIONS = {
        checked: true
    }
    
    let options = { ...DEFAULT_OPTIONS }
    
    const reset = () => {
        options = { ...DEFAULT_OPTIONS }
    }
</script>

<input type="checkbox" bind:checked={options.checked} />
<button on:click={reset}>Reset</button>

See the REPL.

This one works well. However, when I try to use an nested object, then the DEFAULT_OPTIONS object is mutated like the options variable. The reset function doesn't work then anymore:

<script>
    const DEFAULT_OPTIONS = {
        nested: {
            checked: true
        }
    }
    
    let options = { ...DEFAULT_OPTIONS }
    
    const reset = () => {
        options = { ...DEFAULT_OPTIONS }
    }
</script>

<input type="checkbox" bind:checked={options.nested.checked} />
<button on:click={reset}>Reset</button>

See the REPL.

Any idea why?

johannchopin
  • 13,720
  • 10
  • 55
  • 101

0 Answers0