Reputation: 103
My search bar component redirects the user to the search page like so
const handleSearch = () => {
goto(`/movies/search/${searchValue}`);
};
src/components/searchBar
<script>
import { goto } from '$app/navigation';
import searchIcon from '../assets/icon-search.svg';
export let placeholder;
let searchValue = '';
const handleSearch = () => {
goto(`/movies/search/${searchValue}`);
};
</script>
<form class=" ml-5% mt-6 pb-6 flex " on:submit|preventDefault={handleSearch}>
<label class=" relative ">
<input
class=" w-full py-2 pl-10 pr-2 bg-[transparent] border-none text-text text-lg font-light caret-primary placeholder:font-light focus:outline-none "
type="text"
{placeholder}
bind:value={searchValue}
/>
<div class=" absolute top-[50%] left-0 translate-y-[-50%] ">
<img src={searchIcon} alt="" loading="lazy" />
</div>
</label>
</form>
Then the movie gets fetched on +page.server.js
and rendered in +page.svelte
. Everything is fine.
movies/search/[search_params]/+page.server.js
export const load = async ({ params }) => {
const { search_params } = params;
const fetchSearchedMovies = async () => {
const resp = await fetch(`https://api.themoviedb.org/3/search/movie? api_key=${TMDB_API_KEY}&language=en- US&query=${search_params}&page=1&include_adult=false`
);
const data = await resp.json();
return data.results;
};
return {
searchResults: fetchSearchedMovies()
};
};
/movies/search/[search_params]/+page.svelte
<script>
export let data;
const { searchResults } = data;
</script>
<SearchBar placeholder="Search for Movies" />
<CardGrid title="Search Results">
{#each searchResults as movie (movie.id)}
<Card {movie} />
{/each}
</CardGrid>
When I trigger another search, hit enter, it changes the url movies/search/movieYourSearchingFor
, but the content doesn't get updated, i guess because the load function doesn't get re-triggered. When I refresh the page, it then gets loaded.
So my question is how can I make the load function run again, when the search_params change? Can I use invalidate for that? I read in the docs, but Im not sure Im understanding it right.
Thanks for any help.
Upvotes: 7
Views: 4857
Reputation: 184516
It should automatically update, the problem is probably this line:
const { searchResults } = data;
This causes the property to be read just once; change it to:
$: ({ searchResults } = data);
That way the results update when data
changes.
Upvotes: 9