@ipgeotrace/svelte
v0.1.0
Published
Svelte bindings for IPGeoTrace. Resolve the visitor's location once and read it from a reactive store.
Maintainers
Readme
@ipgeotrace/svelte
Svelte bindings for IPGeoTrace. Resolve the visitor's location once and
read it from a reactive store. Built on @ipgeotrace/browser — it uses a publishable
key, so it's safe in the client.
Sign up and grab your publishable key at ipgeotrace.com.
Install
npm add @ipgeotrace/svelte svelteUsage
createVisitorGeo() returns a store that calls me() once on creation. Read it with the $ prefix:
<script lang="ts">
import { createVisitorGeo } from '@ipgeotrace/svelte';
const geo = createVisitorGeo({ publishableKey: 'pk_live_...' });
$: currency = $geo.data?.country?.currency ?? 'USD';
</script>
{#if $geo.loading}
<p>Locating…</p>
{:else if $geo.error}
<p>Couldn't detect your location.</p>
{:else}
<p>Prices in {currency}</p>
{/if}Sharing one lookup across components
Create the store once high in the tree, put it in context, and read it anywhere below — a single
me() call shared everywhere:
<!-- +layout.svelte -->
<script lang="ts">
import { setVisitorGeo } from '@ipgeotrace/svelte';
setVisitorGeo({ publishableKey: 'pk_live_...' });
</script>
<slot /><!-- any child component -->
<script lang="ts">
import { useVisitorGeo } from '@ipgeotrace/svelte';
const geo = useVisitorGeo();
</script>
<span>{$geo.data?.city?.name ?? '—'}</span>What the store holds
Each value is { data, error, loading }, and the store also exposes refresh():
data— theGeoResponse, orundefineduntil it resolves.error— aGeoErrorif the lookup failed (rate_limited,network_error, …).loading—truewhile the request is in flight.refresh()— runme()again. Useful after you know the network changed (e.g. the user toggled a VPN), since the result is never cached — every call reflects the visitor's location right now.
Options
Defer the first call, pass browser-client options, or bring your own client:
createVisitorGeo({ publishableKey: 'pk_live_...', immediate: false });
createVisitorGeo({ publishableKey: 'pk_live_...', options: { timeoutMs: 3_000 } });
import { createBrowserClient } from '@ipgeotrace/browser';
const client = createBrowserClient({ publishableKey: 'pk_live_...' });
createVisitorGeo({ client });See the @ipgeotrace/browser README for the underlying me() client and publishable
keys.
