EA Dee
EA Dee

Reputation: 49

onMount inside a function won't re-trigger when a reactive variable changes

I need to get google maps autocomplete suggestion when I type a word on input.

maps.svelte

function inputChange() {
    onMount(() => {
        loader
            .load()
            .then((google) => {
                const map = new google.maps.Map(document.getElementById('map'), mapOptions);

                const markerPickUp = new google.maps.Marker({
                    position: {
                        lat: 14.6012,
                        lng: 120.975
                    },
                    map: map
                });

                const displaySuggestions = function (predictions, status) {
                    if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) {
                        predictionsArray = [];
                        return;
                    }

                    predictionsArray = predictions;
                    console.log(predictionsArray);
                };

                const service = new google.maps.places.AutocompleteService();
                const sessionToken = new google.maps.places.AutocompleteSessionToken();

                service.getPlacePredictions(
                    { input: $bookDetails.dropOffLocation, sessionToken: sessionToken },
                    displaySuggestions
                );
            })
            .catch((e) => {
                console.log(e);
            });
    });
}

$: $bookDetails.dropOffLocation, inputChange();

I tried to log $bookDetails.dropOffLocation after inputChange() just to see if it's bind on the input and it is. Also, the code works well without the onMount() but it's giving me errors on my terminal. It says windows not defined and it has to do with google maps. I think it needs to load the dom first that's why it gives error. I'm using @googlemaps/js-api-loader.

Upvotes: 0

Views: 497

Answers (1)

brunnerh
brunnerh

Reputation: 184607

onMount registers a callback that executes when the component is mounted. It is not intended to be called multiple times and only ever will invoke the callback once during the lifecycle of a component.

If you just want to make sure that the component is already mounted when executing some logic, you can set a flag and use that as a guard. E.g.

let mounted = false;
onMount(() => mounted = true);

$: {
  $bookDetails.dropOffLocation;
  if (mounted) inputChange();
}

Upvotes: 2

Related Questions