Skip to content
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

replaceState in onMount does not update the $page store #11492

Open
hyunbinseo opened this issue Dec 31, 2023 · 0 comments · May be fixed by #11994
Open

replaceState in onMount does not update the $page store #11492

hyunbinseo opened this issue Dec 31, 2023 · 0 comments · May be fixed by #11994
Labels

Comments

@hyunbinseo
Copy link
Contributor

Describe the bug

When the replaceState is used to trim the URL search params,

// /src/routes/cookie/+page.ts

export const load = () => ({ color: '#fff' });
<!-- /src/routes/cookie/+page.svelte -->

<script>
  import { replaceState } from '$app/navigation';
  import { page } from '$app/stores';
  import { onMount } from 'svelte';

  onMount(() => {
    // Trim URL search params and leave the pathname only.
    if ($page.url.search) replaceState($page.url.pathname, $page.state);
  });
</script>

The $page store accessed by the top +layout.svelte is not updated.

Reproduction

Open the StackBlitz reproduction and click the hyperlinks in-order.

  1. /cookie?query
  2. Home
  3. /cookie?query

When navigating from / to /cookie?query for the first time.

URL string in layout: /
$page.data in layout: {}
page data in /cookie: {"color":"#fff"}

When navigating from / to /cookie?query for the second time. (expected behavior)

URL string in layout: /cookie?query
$page.data in layout: {"color":"#fff"}
page data in /cookie: {"color":"#fff"}

Logs

No response

System Info

System:
	OS: Linux 5.0 undefined
	CPU: (8) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
	Memory: 0 Bytes / 0 Bytes
	Shell: 1.0 - /bin/jsh
Binaries:
	Node: 18.18.0 - /usr/local/bin/node
	Yarn: 1.22.19 - /usr/local/bin/yarn
	npm: 9.4.2 - /usr/local/bin/npm
	pnpm: 8.10.5 - /usr/local/bin/pnpm
npmPackages:
	@sveltejs/adapter-auto: ^3.0.1 => 3.0.1 
	@sveltejs/kit: ^2.0.6 => 2.0.6 
	@sveltejs/vite-plugin-svelte: ^3.0.1 => 3.0.1 
	svelte: ^4.2.8 => 4.2.8 
	vite: ^5.0.10 => 5.0.10

Severity

serious, but I can work around it

Additional Information

Workaround using the history.replaceState API shows error in the console.

onMount(() => {
  if ($page.url.search) history.replaceState(history.state, '', $page.url.pathname);
});

Avoid using history.pushState(...) and history.replaceState(...)as these will conflict with SvelteKit's router. Use the pushState and replaceState imports from $app/navigation instead.

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

Successfully merging a pull request may close this issue.

2 participants