Skip to content

On Destroy

Is a function that safely calls a function when the component is destroyed, 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_destroy} from "@sveu/shared"

    on_destroy(() => {
        console.log("Component destroyed")
    })
</script>

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

๐Ÿ‘ป Arguments

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

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { onDestroy } from "svelte"

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

/**
 * Call onDestroy() if it's inside a component lifecycle, if not, do nothing.
 *
 * @param fn - the function to be called when the component is destroyed
 *
 * @returns true if onDestroy() is called, false if not
 */
export function on_destroy(fn: Fn) {
    try {
        onDestroy(fn)

        return true
    } catch {
        return false
    }
}

Last update: 2023-03-07