Search code examples
javascriptsvelteserver-side-renderingsveltekitsupabase

How to pass in parameters from client side to server side code in Sveltekit?


I've been trying to run a query to a Supabase database that needs a dog breed passed through and will return metrics about it, the breed is defined on the client side. I was able to get the server side query to run but the value is not going through.

+page.svelte

export let metrics;
  export let data;

  const getAllDogs = async () => {
    const { metrics: data } = load({ dog: dog_val });
    metrics = data;
  };
  
  onMount(async () => {
    getAllDogs();
  })


+page.server.js

import supabase from "../../lib/db";

//Method to get all dog breeds
export const load = async ({dog}) => {
  const getAllMetrics = async () => {
    try {
      let { data, error } = await supabase
        .from("dogs")
        .select(
          "avg_size, avg_obedience, avg_compassion, avg_health, avg_cleanliness, avg_energy"
        )
        .eq("Breed", dog);
      console.log(data)
      console.log(dog)
      return data;
    } catch (e) {
      console.error(e);
    }
  };
  return {
    metrics: getAllMetrics(dog)
  }
};

Solution

  • The easiest way I know how to do this is to create an api under src->api->dogs->+server.js. Make a call to your database in the API and then in your client you can make a function that will hit your API and return the data. This way you also could update the data using a dropdown or something like that if you do not want to refresh the page.

    I have this set up on an onload but normally you would probably call this function with a button or dropdown or some other way of setting breed if you need to somehow set the param "breedToSearch". If you are sending the breed in your URL from your route you can pull it from your url, or if you are trying to set it in the page before you navigate to this page you can use the store to set the value before you navigate and then pull the value from the store when this page loads.

    This is just an example of how you would do it using onmount, it's up to you to decide how you want to get your param set before you make the fetch call.

    +page.svelte
      //set empty array for dogs if getting array
      let dogs = []
      //set param somehow for breedToSearch
      let breedToSearch = "lab"
    
      async function getAllDogs {
    
           const response =  await fetch('/api/dogs?dog=${breedToSearch}', {
                    method: 'GET',
                });
            let newData = await response.json();
            dogs = newData.message;
    
      
      onMount(async () => {
        getAllDogs();
      })
    
    
    }
    
    +server.js (in the src-api-dogs directory)
    /** @type {import('./$types').RequestHandler} */
    export async function GET({ url }) {
    //get the dog param sent in the fetch call
    const dog = url.searchParams.get('dog')
    
    const dogsFromDB = -----call to database----
    
    return new Response(JSON.stringify({ message: dogsFromDB }), { status: 200 })
    }