Skip to content

Svelte Lifecycle Functions Not Being Called as Expected #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
matusbarany04 opened this issue Sep 5, 2023 · 2 comments
Closed

Svelte Lifecycle Functions Not Being Called as Expected #215

matusbarany04 opened this issue Sep 5, 2023 · 2 comments

Comments

@matusbarany04
Copy link

Description:

In my Svelte component, I've implemented several lifecycle functions like onMount, onDestroy, beforeUpdate, afterUpdate, and tick. Only onDestroy and tick are being called inside a console, the other lifecycle functions aren't producing any output.

Steps to Reproduce:

Create a following Svelte component with all the lifecycle functions:

<script>
  import { onMount, beforeUpdate, afterUpdate, onDestroy, tick } from 'svelte';

  let count = 0;

  onMount(() => {
    console.log("onMount: Component has mounted");
  });

  beforeUpdate(() => {
    console.log(`beforeUpdate: About to update. Current count: ${count}`);
  });

  afterUpdate(() => {
    console.log(`afterUpdate: State has updated. Current count: ${count}`);
  });

  onDestroy(() => {
    console.log("onDestroy: Component will be destroyed");
  });

  async function increment() {
    count += 1;
    await tick();
    console.log(`tick: DOM updated after incrementing count to ${count}`);
  }
</script>

<button on:click={increment}>
  Increment ({count})
</button>

It seems like the bundle.js file created from rollup config doesn't include any of the other functions

function instance$2($$self, $$props, $$invalidate) {
        let count = 0;
        
        onDestroy(() => {
	        console.log("onDestroy: Component will be destroyed");
        });
        
        async function increment() {
	        $$invalidate(0, count += 1);
	        await tick();
	        console.log(`tick: DOM updated after incrementing count to ${count}`);
        }
        
        return [count, increment];
}

Expected Behavior:

The console should show logs from all lifecycle functions: onMount, beforeUpdate, afterUpdate, and tick.

Actual Behavior:

Only the tick and onDestroy are called

Additional Information:

Svelte version: 4.2.0
rollup-plugin-svelte version : 7.1.6
@matusbarany04
Copy link
Author

It seems to have been a problem with svelte 4 imports

sveltejs/svelte#8953

changing
import {onMount} from "svelte";
to
import {onMount} from "svelte/internal";
fixed my issue

@dummdidumm
Copy link
Member

Do this instead: sveltejs/svelte#8953 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants