good way to filter items from writable store to display in svelte?

1.8k views Asked by At

Is there a better way to do this?

<script>
    import recipeStore from '../../recipeStore';
    export let id;  /* I got this id from the url param */
</script>

<div>
    {#each $recipeStore as recipe }
        {#if recipe.id == id}
        <p>{recipe.name}</p>
        {/if}
    {/each}    
</div>

Thanks!

1

There are 1 answers

5
grohjy On

You can filter your store-data inside the script tag:

<script>
  import {counts} from "./store.js"
  let id=0;
  let mycounts
  const filt=(value)=>{
    mycounts=$counts.filter(count => count.id == id);
    console.log("mycounts: ",mycounts)
  }
  $: filt(id)
</script>

You can use $: to observe the change in a variable. In my example when id changes the filt(id) function is called.

Here is REPL: https://svelte.dev/repl/77f92f3d3ca149dfa5475035cbbffeb5?version=3.29.0