I am trying to write a Pokedex SvelteKit app (as a tutorial from James Q Quick). When I save my index.svelte file - it says the error in the title of this question.
My index.svelte code is as follows:
<script>
import Nav from '../components/nav.svelte'
import {pokemon} from '../stores/pokestore'
import PokemanCard from "../components/pokemanCard.svelte"
let searchTerm = "";
let filtered = [];
$: { // Reacts to any data that changes ($: {what will happen when data changes})
if (searchTerm !== pokemon.searchTerm) {
searchTerm = pokemon.searchTerm;
filtered = filtered(pokemon.pokemons, searchTerm);
}
}
</script>
<svelte:head>
<title>Svelte Kit Pokedex</title>
</svelte:head>
<!-- All HTML Work -->
<h1 class="text-4xl text-center m-8 uppercase">SvelteKit Pokedex</h1>
<input type="text" class="w-full rounded-md text-lg p-4 border-2 border-gray-200" placeholder="Search Pokemon" bind:value={searchTerm}>
<style>
</style>
<div class="py-4 grid gap-4 md:grid-cols-2 grid-cols-1">
{#each $filtered as pokeman}
<PokemanCard pokeman={pokeman} />
{/each}
</div>
How do I fix this?
Thanks :)
filtered is just an array, not a svelte store (or entity that exposes a subsribe() method) so you can't use the $ shorthand to subscribe to it. Just iterate it as an array (without the $).
{#each filtered as pokeman}
...
{/each}
But is pokemon a store? if so you'll need to subscribe to it in the reactive statement to see the changes.
<script>
import Nav from '../components/nav.svelte'
import {pokemon} from '../stores/pokestore'
import PokemanCard from "../components/pokemanCard.svelte"
let searchTerm = "";
let filtered = [];
$: if (searchTerm !== $pokemon.searchTerm) {
searchTerm = $pokemon.searchTerm;
filtered = filtered($pokemon.pokemons, searchTerm);
// *Note: I'm not sure where this 'filtered()' method is coming from but it will conflict with your `filtered` array variable.
}
</script>
<svelte:head>
<title>Svelte Kit Pokedex</title>
</svelte:head>
<!-- All HTML Work -->
<h1 class="text-4xl text-center m-8 uppercase">SvelteKit Pokedex</h1>
<input type="text" class="w-full rounded-md text-lg p-4 border-2 border-gray-200" placeholder="Search Pokemon" bind:value={searchTerm}>
<style>
</style>
<div class="py-4 grid gap-4 md:grid-cols-2 grid-cols-1">
{#each filtered as pokeman}
<PokemanCard pokeman={pokeman} />
{/each}
</div>
Alternatively you could make use of a svelte derived store for your filtered collection, in which case you would use the $ shorthand in iterating it
<script>
import { derived } from 'svelte/store';
import { pokemon } from './stores.js';
const filtered = derived(
pokemon,
$pokemon => $pokemon.pokemons.filter(p => /* your filter logic */ )
);
</script>
<div class="py-4 grid gap-4 md:grid-cols-2 grid-cols-1">
{#each $filtered as pokeman}
<PokemanCard pokeman={pokeman} />
{/each}
</div>