Issue
am new to svelte and svelteKit in general and am trying to load data from api and I followed the sveltekit todo sample code. It's working well for initial rendering and a
tag onClick but in div on:click
am updating url parameters api getting called and returns data but PageData
object not updating.
Here I have attached my onClick
import { goto } from '$app/navigation';
const adhigaramClick = (adhigaram: string) => {
selectedAdhigaram = adhigaram
$page.url.searchParams.set('adhigaram',adhigaram);
goto(`?${$page.url.searchParams.toString()}`);
}
Here I have attached the api call (+page.server.ts
)
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);
};
+page.svelte.ts
file to get the response data(PageData
)
import type { PageData } from './$types';
export let data: PageData;
$: console.log(data);
a
tag click is working fine page re rendering
<a href={`?paal=${paal.keyword}`} >
{paal.titleTamil}
</a>
Solution
Invalidation is probably what you need.
SvelteKit tracks the dependencies of each
load
function to avoid re-running it unnecessarily during navigation. For example, aload
function in a root+layout.js
doesn't need to re-run when you navigate from one page to another unless it referencesurl
or a member ofparams
that changed since the last navigation.A
load
function will re-run in the following situations:
- It references a property of
params
whose value has changed- It references a property of
url
(such asurl.pathname
orurl.search
) whose value has changed- It calls
await parent()
and a parentload
function re-ran- It declared a dependency on a specific URL via
fetch
ordepends
, and that URL was marked invalid withinvalidate(url)
- All active load functions were forcibly re-run with
invalidate()
If a
load
function is triggered to re-run, the page will not remount — instead, it will update with the newdata
. This means that components' internal state is preserved. If this isn't want you want, you can reset whatever you need to reset inside anafterNavigate
callback, and/or wrap your component in a{#key ...}
block.
https://kit.svelte.dev/docs/load#invalidation
Answered By - FlippingBinary
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.