Reactive Parameters

A common requirement is to change search criteria, such as country or language, based on user input. This example demonstrates the idiomatic Svelte approach to re-rendering a component when its fundamental parameters change by using the {#key...} block.

Live Demo

Select a new region or language from the dropdowns below. The autocomplete component will reset, and its search queries will use the new parameters.

powered by
powered by Google

How It Works

This pattern is crucial for ensuring the component re-initialises with the Google Maps API when its core search parameters change. Here’s the breakdown:

  1. Reactive State: The `requestParams` object is created with `$state`, making it reactive. The `bind:value` directive on the `select` elements automatically updates this state when the user makes a selection.
  2. Triggering a Reset: The `onchange` event on the dropdowns calls `resetComponent()`. This function's only job is to assign a new empty object {} to our `componentKey`. In JavaScript, every new object is unique, so this effectively changes the key's value every time.
  3. The `{#key}` Block: The `PlaceAutocomplete` component is wrapped in a `{#key componentKey}` block. Svelte monitors the value of the key. When the key changes, Svelte destroys the component and all its children, then recreates them from scratch.
  4. Passing a Snapshot: We pass `$state.snapshot(requestParams)` to the component. This gives the component the *current* values of the parameters upon creation but prevents it from reacting to further changes *until* it is recreated by the `{#key}` block. This ensures a clean re-initialisation.

Full Code Example

Here is the complete code for this example. Use it as a guide for implementing reactive parameters in your own application.

<script lang="ts">
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
// Google Maps API key
const PUBLIC_GOOGLE_MAPS_API_KEY = '___YOUR_API_KEY___';

// Error handler function
let onError = (error: string) => {
	console.error('Places Autocomplete Error:', error);
};
// Response handler function
let onResponse = (response: any) => {
	console.log('Place Selected:', response);
};

 // List of accepted AutocompleteRequest properties
let requestParams = $state({
	language: 'en-gb',
	region: 'GB'
});	

// Unique key
let unique = $state({}); // every {} is unique, {} === {} evaluates to false
let resetComponent = () => {
	unique = {};
};

// Region options
const regions = $state([
	{ value: 'GB', label: 'United Kingdom' },
	{ value: 'GR', label: 'Geece' },
	{ value: 'IT', label: 'Italy' }
]);
let selectedRegion = $state('GB');

// Language options
const languages = $state([
	{ value: 'en-gb', label: 'English (United Kingdom)' },
	{ value: 'el', label: 'Geeek' },
	{ value: 'it-it', label: 'Italian (Italy)' },
	{ value: 'ru', label: 'Russian' }
]);
let selectedLanguage = $state('en-gb');

// Handle change
let handleChange = (e: Event) => {
	const target = e.target as HTMLSelectElement;
	const value = target.value || '';
	const propTarget = target.dataset.value || '';
	switch (propTarget) {
		case 'region':
			requestParams.region = value;
			break;
		case 'language':
			requestParams.language =  value;
			break;
		default:
			break;
	}
	resetComponent();
};
</script>

<label for="region">Region</label>
<select 
	id="region" 
	name="region" 
	bind:value={selectedRegion} 
	onchange={handleChange} 
	data-value="region">
{#each regions as r}
	<option value={r.value}>
		{r.label}
	</option>
{/each}
</select>
		

<label for="language">Language</label>
<select
	id="language"
	name="language"
	bind:value={selectedLanguage}
	onchange={handleChange}
	data-value="language">
	{#each languages as r}
		<option value={r.value}>
			{r.label}
		</option>
	{/each}
</select>


{#key unique}
	<PlaceAutocomplete 
		{onError} 
		{onResponse} 
		requestParams={$state.snapshot(requestParams)}
		{PUBLIC_GOOGLE_MAPS_API_KEY} 
	/>
{/key}		

2025 Places Autocomplete Svelte.