Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte Component Not Reactive When Using Global Script

I’m using SvelteKit to build an app, and I import an external script (Apple’s MapKit JS) in my app.html like this:

<script src="https://cdn.apple-mapkit.com/mk/5.72.88/mapkit.js"></script>

I then have a Map.svelte component that loads a point on a map using my own Airport object. I have omitted extra details that aren’t relevant with ...:

// === Map.svelte ===

<script lang="ts">
import { onMount } from 'svelte'
import type { Airport } from '$lib/data/typesAirports'

export let airport:Airport
let mapWrap:HTMLDivElement
let map: mapkit.Map

onMount(() => {
  setupMap(airport)
})

function setupMap(airport){
  //Setup my mapkit object with my token
  mapkit.init(...)

  //Set my map instance
  map = new mapkit.Map(mapWrap, {...})

  //Create pin on map using airport latitude and longitude
  const annotation = new mapkit.MarkerAnnotation(...airport latitude & longitude...)
  map.addAnnotation(annotation)
}
</script>

<!-- Map in HTML -->
<div bind:this={mapWrap}></div>

So far, this works great. But when I change my airport property in the parent component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

//=== Parent.svelte ===

<Map airport={airport} />

…there is no reactivity in the Map component. My suspicion is this is because things that happen in onMount are excluded from that reactivity, but I’m unclear on how that works.

If I try something like this, I get an error that airport is undefined:

$: setupMap(airport)

How can I preserve reactivity in a component like this that relies on an external JS library? Or more specifically, how do I get my map to reload when the airport changes?

>Solution :

onMount happens once, when the component mounted to the DOM. The approach using a reactive statement is the correct one.

If a property can be uninitialized/undefined you can simply guard against that using an if statement:

$: if (airport) setupMap(airport)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading