Skip to content

On Mount

Is a function that safely calls a function when the component is mounted, without throwing an error if it's inside a component lifecycle or not, in case if this function is called outside a component lifecycle it will do nothing.

๐ŸŽฌ Usage

<script>
    import {on_mount} from "@sveu/shared"

    on_mount(() => {
        console.log("Component mounted")
    })
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ‘ป Arguments

Name Description Type Required
fn The function to call when the component is mounted. () => void Yes

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { onMount } from "svelte"

import type { Fn } from "../utils"

/**
 * Call onMount() if it's inside a component lifecycle, if not, do nothing.
 *
 * @param fn - the function to be called when the component is mounted
 *
 */
export function on_mount(fn: Fn) {
    try {
        onMount(fn)
    } catch {
        // do nothing
    }
}

Last update: 2023-03-07