11

In SvelteKit navigation goto allows to pass state in the second argument such as:

import { goto } from '$app/navigation';

// ...

goto('/login', { state: { foo: 'bar' } });

The documents do not make it clear how state can be consumed/retrieved after the resulting navigation has occurred. state does not seem to be present on $page nor seems to be available on $navigating.

How do you consume state passed to second argument of goto()? Is it currently missing and you have to create your own writable store to manage this state?

This is an adapter-static SvelteKit application.

2 Answers 2

5

The state being referred to is the one held on the history stack of your browser tab or window.

You can access it in two different ways:

  • directly by reading the value of history.state, although not very useful in practice as it returns the value of the state at the top of the history stack only
  • by listening to popstate events, which will fire when the history stack is 'popped' (ex.: hitting back button on your browser or navigating programatically), in which case the state will be a property on the synthetic event object passed to the listener when the event fires
Sign up to request clarification or add additional context in comments.

3 Comments

You are indicating that sveltekit has no built in way such a store to interact with that state added to history? Or are you saying there is a store for history available via kit? A bit unfortunate as something like react-router-dom that has the same exact mechanism for passing state on navigation, provides the ability to access that state in its equivalent of $page
To my knowledge, there is no specific mechanism in place in Svelte to handle History's state, as it is a mechanism that is not particular to Svelte. Afaik, react-router-dom relies on the history npm package, where Svelte interacts with the standard History API provided by your browser, so they're a bit different.
You can still add a listener for the popstate event without too much complexity, however, locating it in your top-most container (e.g. your root layout). Note that this would have to be client-side code only, as there's no concept of history server-side (and no access to the History API on the server).
2

Summary for Beginners: As it seems on SvelteKit docs, there's no direct state communication between routes. Every option is about using a different app layer than the routes itself. The only option not mentioned by @Thomas Hennes above, is the use of store.

1 Comment

Thanks for the doc link, I used {replaceState: true} in my case and it works great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.