Tutorials on Leaflet

Learn about Leaflet from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Svelte Lifecycle Method - onMount

In Svelte, a component's onMount lifecycle method is called after the first time the component has been rendered to the DOM. For example, if you have a component that is wrapped within an {# if} block, then when this block's conditional statement is fulfilled, the component will be mounted to the DOM, at which point onMount will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that DOM elements within the component will be available for your code to access/manipulate. Here's a template of how the onMount lifecycle method is used inside of a component: Considered the most commonly used lifecycle method, onMount covers a wide diversity of use cases such as... Below, I'm going to show you: When you visit the G-Mail login page, you will notice that the e-mail address input field is automatically focused: This convenience automates away the initial click (or tabbing) into the input field that the user would have to do before being able to type in their e-mail address. Using the onMount lifecycle method, the focus can be moved to an input field when the component is initially rendered. Visit this simple Svelte REPL demo to see how to automatically focus an input field using the onMount lifecycle method: Demo - onMount Lifecycle Method - Login Form When you load the Svelte REPL, the e-mail address input field is automatically focused (indicated by its blue outline). The bind:this directive sets the variable it's passed a reference to an element's DOM node. Here, the emailAddressInput variable is set to the <input type="email" /> element. Since onMount runs after the component has been rendered, the input field will exist by the time this method is executed. Therefore, emailAddressInput will have been set to this input field, and the focus can immediately be moved to it. Note : Automatically focusing into an input field may skip over vital information a user using assistive technologies should be aware of. This may have negative implications on the accessibility of the application. Lazy-loading content reduces the initial load time of an application and reduces bandwidth by delivering only what the client has requested. Imagine having to wait seconds or minutes for a large webpage containing tables with thousands or millions of rows to be downloaded before seeing any content in your browser. Before the webpage finishes downloading, you would have most likely moved on to a different webpage. Wouldn't it be better if you were presented some content immediately (to keep you engaged), and then be shown a "loading" message when you request to view a large table? The onMount lifecycle method can be used to retrieve data from a remote API. This data can then be set to a variable in your component, which will cause the component to only re-render the part of the DOM that's affected by changes to this variable. This is especially useful for lazy-loading a table that contains many records. Visit this simple Svelte REPL demo to see how to fetch motor vehicle collisions data from the NYC Open Data API and render this data as rows of cells in a table using the onMount lifecycle method: Demo - onMount Lifecycle Method - NYC Open Data API Here, we are fetching data from the NYC Open Data Portal, particularly on NYC motor vehicle collisions . Each record of this dataset features the location of the accident, the vehicles involved, the number of fatalities, etc. For fetching data, we are using the native fetch method. The fetch method returns a Promise , so we will schedule an async callback to run when the component is mounted. While the data is being fetched, a "Loading..." message is presented to the user to notify them of the table's status (initially, isLoading is set to true , and this flag toggles this message on/off). Once the data is downloaded and parsed, the collisions variable is set to this data and the isLoading flag is set to false. As a result, the "Loading..." message disappears, and a select number of features of each record are displayed in the table. Note : Alternatively, this can be accomplished with an {#await } block ! Note : Since onMount is not ran during server-side rendering, if you need to fetch data within a component after its initial rendering, then it must be done within onMount and not outside at the top-level of <script /> . Note : Since async functions always return a Promise , onMount cannot return an unmount function since it must synchronously return a value. Event listeners execute code when an event, such as moving the mouse, takes place on the element it's binded to. In component-based applications, event listeners are registered once the component has been rendered to the page. Visit this simple Svelte REPL demo to see how to add an event listener on the window "resize" event using the onMount lifecycle method: Demo - onMount Lifecycle Method - Window Resize As you resize the browser window, notice how the window width displayed in the view changes. Just before the component is unmounted from the DOM, the unmount callback returned from onMount will be executed. This will remove this event listener from window , which will avoid memory leaks in legacy browsers, such as Internet Explorer, that do not automatically garbage-collect event handlers of removed DOM elements. When embedding a widget/plugin from a third-party library, those libraries will need to know where to place the widget/plugin in your application. For example, to display Google Maps via Google's Maps JavaScript API , the first argument to the google.maps.Map method is a reference to an existing DOM element (often document.getElementById('map') ) on the page where you wish to place the map. Visit this simple Svelte REPL demo to see how to embed a Leaflet map into your Svelte application using the onMount lifecycle method: Demo - onMount Lifecycle Method - Leaflet Map The <svelte:head /> element inserts elements into the <head /> element of the document. In this context, we are adding the Leaflet CSS and JavaScript files. By using <svelte:head /> , it keeps all Leaflet-related code encapsulated within a single component that contains all code related to rendering the Leaflet map. When the component is mounted, the <div id="map" /> container element will exist when the onMount callback is executed. The Leaflet library will be able to find this element and initialize the map. Note : This can also be done with Google Maps, but this example uses Leaflet since the Google Maps API requires an API key. To generate this API key, you must provide Google with your billing information in their Google Cloud Platform, and I felt this would add more an unnecessary obstacle to learning how load an embeddable widget/plugin with onMount . Note : If the Leaflet map is toggled on/off, then return an unmount callback that runs map.remove() to destroy the map and clear all of its related event listeners. Let's take the focus input example and refactor it. Instead of having the onMount code (and its contents) in the same file as the component, let's move it into an external module. Demo - onMount - External Module ( onMount.js ) ( App.svelte ) Notice how the bind:this directive was removed from the e-mail address input field. This is because the reference of the DOM node captured by this directive cannot be passed as an argument to the onMountFocusInput method. The DOM node reference will not be available when this method is executed since it is called at the top-level of the <script /> tag. Instead, we can pass an id value so that onMount can query for the input field element once the component that contains it is rendered. Additionally, by moving this onMount code outside of the component, it can be reused for other components that may need to automatically focus an input field when they are rendered to the page. If you have built React applications, then you will have probably noticed how similar onMount is to componentDidMount / useEffect . Try rewriting some of the those components that use componentDidMount / useEffect as Svelte components that use onMount . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - onMount

Svelte Lifecycle Method - onDestroy

In Svelte, a component's onDestroy lifecycle method is called before the component is removed from the DOM. For example, if you have a component that is wrapped within an {#if} block and it is currently rendered to the DOM, then when this block's conditional statement evaluates to false , the component will be unmounted from the DOM, at which point onDestroy will be called. Being able to schedule a callback to run at this phase of a component's lifecycle ensures that cleanup-related operations can be ran and previous application states can be resumed. Here's a template of how the onDestroy lifecycle method is used inside of a component: Compared to the function returned from onMount , there are specific reasons for using onDestroy : As a vital lifecycle method, onDestroy covers a wide diversity of use cases such as... Below, I'm going to show you: When a modal dialog is closed, the focus should return back to the element that opened the modal dialog. Not doing so would hurt the experience of users who rely on keyboards and/or assistive technologies to navigate through webpages. To rescue the focus: Visit this simple Svelte REPL demo to see how to refocus a previous element using the onDestroy lifecycle method: Demo - onDestroy Lifecycle Method - Modal ( Modal.svelte ) When the "Open Modal" button is clicked, it sets the isModalOpened flag to true , which causes the <Modal /> component to be rendered to the page. When an instance of the <Modal /> component is created, its <script /> block is executed, and previouslyFocused is set to document.activeElement , which references the most-recently focused element (the "Open Modal" button). Notice that the "Close Modal" button in the modal dialog is focused due to its autofocus attribute. When you click the "Tab" key, the focus is trapped within the modal dialog (each press moves the focus to each link, followed by the "Close Modal" button, and back, repeating in a cycle), which prevents the focus from escaping the modal dialog. When you press the "ESC" key or click the "Close Modal" button, then the "close" event is dispatched, which will execute the closeModal function, set the isModalOpened flag to false and remove the modal dialog from the DOM. Before the modal dialog is unmounted, the callback passed to onDestroy will be ran. The focus will resume back to the previously focused element, the "Open Modal" button. Note : In Firefox and Safari, document.activeElement references the <body /> element in an <iframe /> element (where the Svelte REPL displays the result of the Svelte code). In the demo, a reference to the "Open Modal" button is passed to the <Modal /> component as a prop, and it is manually used as the previously focused element if document.activeElement references the <body /> element. Removing event listeners is necessary for avoiding memory leaks in older browsers that don't automatically garbage-collect event handlers of removed DOM elements. A common pattern for registering and unregistering event listeners in Svelte is to perform these actions during the onMount and onDestroy lifecycle methods respectively. Visit this simple Svelte REPL demo to see how to remove event listeners in your Svelte application using the onDestroy lifecycle method: Demo - onDestroy Lifecycle Method - Removing Event Listeners (Window Resize) ( WindowResize.svelte ) Resizing the window updates the printed width value. By debouncing the event handler, the resize event listener will only call the event handler after the resize event has stopped firing for 300ms. Limiting the rate at which the event handler is executed will yield performance gains, especially in much larger applications. To trigger the onDestroy lifecycle method, press the "Toggle" button to toggle off the <WindowResize /> component. This will remove the registered resize event listener on the window object. If, instead, the event listener was binded to an element within the component, then the event listener can be binded to the element in onMount since the element will have been rendered by the time onMount is called. Likewise, the event listener can be removed from the element in onDestroy since onDestroy occurs just before the element is removed from the DOM, which means the element still exists when removing this event listener. To understand how a UI change can affect a user's engagement with your application, you might collect a set of metrics, such as bounce rate and average session duration, via Google Analytics or software custom-built to log this information. A simple metric to integrate into your application is tracking how long a user stays on a page. A rudimentary implementation of this would involve starting a timer the moment the user visits the page, and then stopping the timer the moment they exit the page. Visit this simple Svelte REPL demo to see how to log user activity in your Svelte application using the onDestroy lifecycle method: onDestroy Lifecycle Method - Logging User Activity ( RedditArticle.svelte ) In this example, each tab represents a "subreddit," a topic-specific, online community on Reddit ( r/science , r/technology and r/worldnews ). Clicking on any of these tabs will display a list containing the most popular articles for the corresponding subreddit. The <RedditArticles /> component is mounted anytime the user clicks on any of the subreddit tabs. Upon switching from one subreddit to another, the current <RedditArticles /> component will be unmounted, and a new <RedditArticles /> component will be mounted. The subreddit prop is passed to ensure the articles for the currently selected subreddit are loaded. When an instance of the <RedditArticles /> component is created, this represents the user landing on a new "page," and a timer begins to mark this ( let startTime = performance.now(); ). Once the user leaves the "page" (switching to a new subreddit), the onDestroy lifecycle method is called, and the difference between the time at which the component is unmounted and the recorded start time is calculated. This difference represents how long the user was on this subreddit before leaving. After performing this calculating, the difference can be sent to an API endpoint to be stored. All of the data collected can then be aggregated and viewed inside of a dashboard. Typically, in component-based architectures, data flows downwards from parents to children (unidirectional). In Svelte, stores allow data to be shared between components, regardless of their relationship in the component hierarchy. A store contains a subscribe method that notifies components of changes to the store's value. When the subscribe method is executed, an unsubcribe method is returned, which cancels a component's subscription to a store when called. Visit this simple Svelte REPL demo to see how to unsubscribe from a Svelte store subscription using the onDestroy lifecycle method: onDestroy Lifecycle Method - Scheduling Store Unsubscriptions ( RedditArticles.svelte ) In this example, the "Logging User Activity" demo has been repurposed with the <Subreddits /> component (the tabs) and the <RedditArticles /> component (the list of subreddit articles) both subscribed to a store named reddit . ( store.js ) currentSubreddit represents the currently selected subreddit (by default, it is r/science). Because the value of currentSubreddit can be modified, this store is a writable store, which means two additional methods are provided alongside the subscribe method: set (sets a new value for the store and synchronously executes every active subcription method of the store) and update (updates a value based on the current value in the store). For convenience, a custom method, setCurrentSubreddit , is made available, and it directly updates the currentSubreddit value. All components subscribed to the store will see the changes. In this case, both the <App /> and <RedditArticles /> components are subscribed to the store for changes to currentSubreddit . Imagine a scenario in which a component is mounted/unmounted many times throughout the lifetime of the application. If unsubscribe is not called upon unmounting the component, then its corresponding subscription will still be alive and will be executed upon future updates to the store even when the component the subscription is tied to has been unmounted. Try this out by commenting out the unsubscribe function call in the <RedditArticles /> component's onDestroy and adding a console.log() statement inside of the subscription function. As you switch tabs from one subreddit to another, watch as more and more messages are printed inside of the console. With so many subscriptions still in memory and not garbage-collected, eventually, this will cause a memory leak. To avoid this situation, the unsubscribe method must be called inside of onDestroy lifecycle method. Note : Subscribing to the store and adding a call to the unsubscribe method inside of many components that rely on the store can become tedious and resemble repetitive boilerplate code. Instead, just import the store and prefix a store value with a $ to auto-subscribe to it. The auto-subscription shorthand will allow components to auto-subscribe to the store and automatically unsubscribe from it when the component is destroyed. Check out the <Subreddits /> component for an auto-subscription example. ( Subreddits.svelte ) For third-party libraries such as Leaflet.js that embed interactive maps into an application, the provide methods for "cleaning-up" when they are removed from the DOM. For example, in the case of Leaflet.js, the remove method destroys the map and its layers and clears all of their corresponding event listeners. Visit this simple Svelte REPL demo to see how to clean-up an embedded Leaflet map in your Svelte application using the onDestroy lifecycle method: onDestroy Lifecycle Method - Clean-Up External/Third-Party Libraries ( LeafletMap.svelte ) When the map is toggled on, the <LeafletMap /> component's onMount lifecycle method is called and initializes a new map on a specified container element. Additionally, a marker icon is displayed, and an event listener is added to this icon. Whenever the icon is clicked, a popup opens above it. Once the map is toggled off, the <LeafletMap /> component's onDestroy lifecycle method is called and destroys the map and the marker and clears all of their corresponding event listeners such as zooming in the map, the opening of the marker icon's popup on clicking, etc. When server-side rendering a Svelte application, only one lifecycle method is called: onDestroy . Particularly, onDestroy is called after the application is rendered. For example, when building the static version of a Sapper application via npm run export , only onDestroy is called. To verify this, simply add a console.log statement into each lifecycle method call and observe the outputted logs in the CLI. ( src/routes/index.svelte ) If you have built React applications, then you will have probably noticed how similar onDestroy is to componentWillUnmount . Try rewriting some of those components that use componentWillUnmount as Svelte components that use onDestroy . If you want to learn more about Svelte, then check out Fullstack Svelte :

Thumbnail Image of Tutorial Svelte Lifecycle Method - onDestroy

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More