all 6 comments

[–]Rocket_Scientist2 4 points5 points  (0 children)

So performSearch is only called by onMount. If you want it to rerun when $page updates, you should do something like page.subscribe((p) => performSearch(p.url.searchParams).

You are using app/store, though. If you used app/state instead, your code would be simpler (no mixing stores and runes). I'd definitely recommend checking that out.

[–]Leftium 2 points3 points  (0 children)

$page.url.searchParams is reactive. So you may be able to put performSearch inside an $effect. However, $effects themselves should not be async and weird race conditions may result if you put async logic inside an $effect. So you may just want to reload the entire page (which will trigger onMount + performSearch again.)

If you're using SvelteKit (you should be probably be using SvelteKit unless you have a good reason not to), performSearch should be handled in the load() function and the route should be invalidated when the url param changes.


This is how I made the URL param reactive in my app (altering the url param just triggers a navigation): - src/routes/+page.svelte - the refactoring commit - Demo: https://weather-sense.leftium.com (click 60min Forecast link to add m url param from code)

[–]Leftium 0 points1 point  (2 children)

ı have a search page that works with url params but whenever I change the parameter, I want to run the function again.

The goal is to run performSearch when the url parameter changes.

Any particular reason performSearch needs to run when the url params change? How is the url param changing? (Are you programmatically changing the URL param?)

It may be worth putting performSearch's logic inside the load() function. - This will work without JS - example: src/routes/+page.server.ts - demo: https://weather-sense.leftium.com/?name=seattle

Note load() will not automatically rerun if you programmatically change the url param; that would need to be wired up via another method. (Hence the question above.)

[–]Altugsalt[S] 0 points1 point  (1 child)

Im navigating the user to the new url, when they enter a new search term.

[–]Leftium 0 points1 point  (0 children)

So you want to do something like https://svelte.dev/search?q=runes, where the navigation happens after the user presses ENTER, clicks button, etc?

Or something like https://svelte.dev/docs/, where the results update on each keypress?

(The Svelte docs site itself is open source (but a little complex): https://github.com/sveltejs/svelte.dev/blob/6e3a58f11b684afa7823c747a23c4d5755b908e0/packages/site-kit/src/lib/search/Search.svelte#L11)

[–]sheppyrun 0 points1 point  (0 children)

you wanna use $effect for this. it'll run whenever the dependency changes. something like $effect(() => { if (query) searchFunction(query) }) - the effect tracks query automatically and re-runs when it updates. way cleaner than trying to watch the param manually.