Finding correct query in api based on url slug

This code is an asynchronous JavaScript function that fetches project data from an external API and processes it to find a specific project based on a URL-friendly version of its name. Here’s a summar

Replace Name_Project with your own name in your api

[slug]/+page.js
import { error } from '@sveltejs/kit';
import { MakeUrlFriendly } from '$lib/utils.js';

export async function load({ fetch, params }) {
  try {
    const response = await fetch('https://api.example.com/data');
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    let posts = data.data;
    let matchingPost = posts.find((matchingPost) => MakeUrlFriendly(matchingPost.name) === params.slug);
    return { matchingPost };
  } catch (e) {
    console.error('Error fetching data:', e);
    throw error(500, 'Error fetching data from API');
  }
}

Last updated