Skip to content

Double component mount on $session change after component change and page refresh in the dev mode #4799

@mihaon

Description

@mihaon

Describe the bug

If I start the svelte kit in the dev mode (npm run dev) then change a *.svelte file and then refresh the http://localhost:3000 page in the browser, then onMount will be called twice (on the first load and on the $session change).

Reproduction

  1. Create the svelte kit app:

src/routes/index.svelte:

<script>
	import {session} from '$app/stores'
	import {onMount} from 'svelte'

	onMount(() => {
		console.log('onMount')
	})
</script>

<div>{$session.counter}</div>

<button type='button' on:click={() => {
	session.update(session => {
		return {
			counter: session.counter + 1
		}
	})
}}>Click me</button>

app.html:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		%svelte.head%
	</head>
	<body>
		<div>%svelte.body%</div>
	</body>
</html>

hooks.js:

export function getSession(event) {
	return {
		counter: 0
	}
}

package.json:

{
  "name": "my-app",
  "version": "0.0.1",
  "scripts": {
    "dev": "svelte-kit dev",
    "build": "svelte-kit build",
    "package": "svelte-kit package",
    "preview": "svelte-kit preview",
    "prepare": "svelte-kit sync"
  },
  "dependencies": {
    "@sveltejs/adapter-auto": "next",
    "@sveltejs/kit": "next",
    "svelte": "^3.48.0"
  },
  "type": "module"
}

svelte.config.js:

import adapter from '@sveltejs/adapter-auto'

export default {
	kit: {
		adapter: adapter()
	}
}
  1. Execute npm install
  2. Execute npm run dev
  3. Open the http://localhost:3000/ page in the browser and open the browser console
  4. Click to the "Click me" button. As you can see, onMount doesn't triggered on click (this is the correct behavior).
  5. Now change the index.svelte file. For example, replace console.log('onMount') to console.log('onMount2')
  6. Refresh the page in the browser (F5, Ctrl+R, etc.)
  7. Click to the "Click me" button

Expected result

onMount is triggered only on the page load and doesn't triggered on click

Actual result

onMount is triggered on the page load and on the click (i.e. on the session.update())

Logs

No response

System Info

@sveltejs/kit: 1.0.0-next.324
@sveltejs/vite-plugin-svelte: 1.0.0-next.42
svelte: 3.48.0
vite: 2.9.7
browser: Chromium 101.0.4951.41
OS: Linux Ubuntu 20.10
nodejs: v17.0.1

Severity

annoyance

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions