Svelte each block rendering only the last item

1.1k Views Asked by At

I'm trying to make a tag input component in svelte and I've encountered a strange #each block behavior. I have the following svelte code

<script>
  import Input from './Input.svelte'
  import Tag from './Tag.svelte'

  export let tagValues = []
  let currentTag = ''

  function handleEnter({ key }) {
    if (key === 'Enter' && currentTag) {
      if (tagValues.indexOf(currentTag) < 0) {
        tagValues = [...tagValues, currentTag]
      }
      currentTag = ''
    }
  }
</script>

<div class="relative">
  <Input bind:value={currentTag} on:keyup={handleEnter}></Input>
  {#each tagValues as t (t)}
    <Tag value={t}></Tag>
  {/each}
  {JSON.stringify(tagValues, null, 2)}
</div>

The idea is to get the input value when the user hits Enter key and add that value as a tag if it isn't present already. Input component behaves the same as input Html element. Tag component only has a value property which is text, this should render all the values of the tagValues array, but only shows the last one. I can confirm that the array includes correctly new tags, because I pasted a stringify version of it to HTML. This is how it looks with 1 tag

One tag rendered

And this is with two tags

Two tags rendered

How can I make this component to render all tags? I have tried to make my each block keyed but nothing changed.

0

There are 0 best solutions below