Joe
Joe

Reputation: 1045

Making checkbox bind:checked value reflect state of values in $store

I've a Writable store containing values whose selected state should be reflected in a group of checkboxes that are written out in an #each loop. I want the checkboxes to show the checked state automatically so that the checkboxes and store are in synch, for instance on coming back to the page after an initial storing of values.

I've made it work, but doing so has meant maintaining a parallel (to the values) checkbox state array which I index into using an index on the #each loop. This seems hacky. It seems that there should be a way to automatically, with only Svelte's checkbox bindings, acheive this.

Here is the hacky workaround I do:

            {#each foobars as foobar, i}
              <li>
                <label for="foobar-{i}">{foobar[1]}</label>
                <input
                  id="foobar-{i}"
                  type="checkbox"
                  bind:group={$foobarStore}
                  value={foobar}
                  bind:checked={foobarCheckboxStates[i]}
                  class="checkbox"
                />
              </li>
            {/each}
...

<script lang="ts">
  // ... inside an async function that fetches data and returns it in a promise which is then used by #await then and subsequent #each loop:
    
      for (const [idx, foobar] of foobars.entries()) {
        if ($foobarsStore && foobar) {
          foobarsCheckboxStates[idx] = $foobarsStore
            .some(item => item[0] === foobar[0])
        } else {
          foobarsCheckboxStates[idx] = false
        }
      }
    
// rest of async function...
</script>

foobarCheckboxStates shouldn't be necessary it would seem. Am I missing something? What I've done works, but doesn't seem best.

Upvotes: 0

Views: 1697

Answers (1)

brunnerh
brunnerh

Reputation: 185225

It is not intended to use group together with checked, if one is updated programmatically, the other does not update (REPL demo).

If you use group, you should determine item state by checking whether the item is in the group array. Likewise if you want to change the state of an item, you should add/remove it to/from the group.

Upvotes: 2

Related Questions