dimanche 27 août 2023

Problem retrieving user data for Supabase query in Sveltekit

I'm loading in a table from Supabase of categories (id, category) that populate a select dropdown. The user selects a category, hits submit, and then it takes them to a category page with a random quote associated with what the category selected. The category page is pulling data from another table in Supabase (id, name, content, category_id) with all the quotes.

The select dropdown is working and so is the routing in the URL based on the category ID of the selection (/category/1, /category/2, etc), but I'm having trouble getting that same category ID into my query for the Category page. It seems like I'm close, but I've been stuck on this for awhile and not sure what else to try at this point.

The main pages related to this issue are /routes/category/[id]/+page.svelte, /routes/category/[id]/+page.server.js, and /routes/Quote.svelte.

Here's the /routes/category/[id]/+page.svelte code:

<script>
    import Quote from "../../Quote.svelte";
    import { page } from "$app/stores";
    
    const category = $page.params.num;
    
    export let data;
    $: ({ quotes } = data);
</script>

<Quote quotes="{quotes}" />

Here's the /routes/category/[id]/+page.server.js code:

import { supabase } from "$lib/supabaseClient";

export async function load() {
  const { data } = await supabase
    .from('quotes')
    .select('*')
    .eq('category_id', 2); // TODO: Retrieve category ID to select random quote
  
  return {
    quotes: data ?? [],
  };
}

And here's the /routes/Quote.svelte code:

<script>
    import { writable } from 'svelte/store';
    export let quotes;
    function getRandomQuote() {
      const randomIndex = Math.floor(Math.random() * quotes.length);
      return quotes[randomIndex];
    }
  
    const randomQuote = writable(getRandomQuote());
  
    function generateNewQuote() {
      randomQuote.set(getRandomQuote());
    }
</script>

{#if $randomQuote}
  <p>{$randomQuote.content}</p>
  <p>{$randomQuote.name}</p>
{/if}
<button on:click={generateNewQuote}>Get Another Quote</button>

I don't know if I'm approaching this the correct way. It feels like I'm close, but maybe I'm way off. I'm new to Sveltekit and trying to understand it better.




Aucun commentaire:

Enregistrer un commentaire