mikemaccana
mikemaccana

Reputation: 123098

Svelte - changing a bound value in a click handler doesn't seem to update it

I have a simple demo app of binding an input using Svelte. This works, but during a click handler on that same element, I wish to reset the bound value.

enter image description here

Specifically I have bound an input to draftMessage and would like to set draftMessage back to an empty string after the message is submitted:

<script>

    let draftMessage = '';

    let handleSendMessageClick = function(event){
        var message = event.target.form.querySelector('input').value
        previousMessages.push(message)
        previousMessages = previousMessages

        // Clear draftMessage
        console.log(`Clearing draftMessage - why doesn't this work?`)
        draftMessage = ''
    }

    let previousMessages = [];
</script>

<h1>Type some things</h1>

<form>
  <input value={draftMessage}/>
  <button on:click|preventDefault={handleSendMessageClick}>Send</button>
</form>

{#each previousMessages as message}
  <p>{message}</p>
{/each}

There is a live demo here

How can I change a bound value in a click handler?

Upvotes: 2

Views: 2214

Answers (1)

Rich Harris
Rich Harris

Reputation: 29585

You forgot bind:, so the value of draftMessage never actually changes, so draftMessage = '' has no effect. You have a couple of options:

  1. Do <input bind:value={draftMessage}> so that by the time you hit that line, draftMessage has a value other than the empty string. (You can now use that value instead of querying the DOM — previousMessages = [...previousMessages, draftMessage]). Demo here
  2. Skip draftMessage entirely, and use the DOM throughout (input.value = ''). Demo here

Upvotes: 3

Related Questions