arraysselectsvelte

How do I get an element in a Svelte array using a value derived from a select element?


I have a list of users which I iterate over to populate a selection pull down but I need to use the selected user to pull their age from the array. I've bound value to the variable select but I can't seem to get the value of users[id=select].age

<script lang="ts">
  import Users from './lib/Users.svelte';
const users = [
    {
      id:1,
      name: 'Andrew',
      age: '39',
    },
    {
      id:2,
      name: 'David',
      price: '80',
    },


  ] as User[];
  let selected = '0';
  let age = users[0].age;
</script>
<div class="min-h-screen bg-slate-800 text-white">
  <main class="max-w-screen-rs mx-auto">

    <select bind:value={selected} class="bg-green-800 text-white" id="userSelect" name="userSelect" size="1">
       <option value="0" selected="selected">Select a user</option>
        {#each users as user}
        <option value={user.id}>{user.category}</option>
        {/each}
    </select>
</main>
</div>

I've tried the following let age = users[id={selected}].age;

but to no avail. I have output to the console the value of selected and it is updating that value but if I try and use it as defined above I just get a blank page no error message nothing just code that won't render


Solution

  • Dependent statements need to be made reactive via $: in Svelte 3/4:

    $: age = users[selected]?.age;
    

    (?. prevents errors if no user is selected, it will fall back to undefined.)