I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a
tag. However, I am facing an issue with updating the url parameters via a div
on:click
event; although the API is being called and returns data, the PageData
object does not update as expected.
Below is my implementation of the onClick
:
import { goto } from '$app/navigation';
const adhigaramClick = (adhigaram: string) => {
selectedAdhigaram = adhigaram
$page.url.searchParams.set('adhigaram',adhigaram);
goto(`?${$page.url.searchParams.toString()}`);
}
Here is the corresponding API call in the +page.server.ts
file:
export const load: PageServerLoad = async ({url, params}) => {
let selectedPaal = "test";
const paramPaal = url.searchParams.get("paal");
const adhigaram = url.searchParams.get("adhigaram");
if (paramPaal) {
selectedPaal = paramPaal;
}
const response = await api('GET', `page/${selectedPaal}${adhigaram ? `/${adhigaram}` : ''}`);
if (response.status === 404) {
return {
data: {} as Page
};
}
if (response.status === 200) {
return {
... (await response.json()) as Data
};
}
throw error(response.status);
};
I also utilize the +page.svelte.ts
file to access the response data (PageData
):
import type { PageData } from './$types';
export let data: PageData;
$: console.log(data);
Lastly, clicking on the a
tag triggers page re-rendering successfully:
<a href={`?paal=${paal.keyword}`} >
{paal.titleTamil}
</a>