sveltekit Hash-based routing

Big_Boulard

I'm pretty new to svelte and especially SvelteKit. Currently, I'm working on 2 projects.

The 1st one is a SPA in which I use svelte-spa-router to manage the different states and bring the ability to navigate back and forward like we would do in an old-school website. This works perfectly :)

The 2nd project is a SvelteKit app. I have 3 use cases:

  1. Search a product
  2. Create a product
  3. Display the top 10 products

In the first place, I thought that it would be interesting to be able to prefetch some kind of JSON data if needed for each use case, but on the other hand, I didn't want to create a route page for each sub use case because I didn't want the page to refresh each time the user makes a simple action. So, I'm using 3 routes to navigate between these 3 "use cases":

src/routes/search_product.svelte
src/routes/create_product_page.svelte
src/routes/show_top_10_products.svelte

Now, I have a problem ... there's 3 steps to create a product page. These 3 steps are represented by the 3 different Svelte components below:

  1. EnterProductBasicInfo.svelte
  2. UploadPictures.svelte
  3. GivePrices.svelte

If the user is in the process of creating a product page and is at step 2), he is shown the UploadPictures.svelte component .... but if he press the back button, he will quit the create_product_page.svelte route instead of getting back to step 1) that is the EnterProductBasicInfo.svelte component.

So, I was thinking that I may use the svelte-spa-router that I've used for the SPA, but I'm asking experts here if there is another built-in solution in SvelteKit to be able to manage routes without refreshing the whole page each time a route changes. If you have some good link about SPA, SSR, preloading vs prefetching, I'll take it cause it's still a bit blurry to me.

Thank you so much for your help.

Bob Fanger

I think adding svelte-spa-router would be overkill.

In SvelteKit pages are rendered on the server (SSR) initially, but once loaded, pages are not refreshed each time a route change. It will behave like a SPA but with autmatic route based code-splitting and data loading built-in. Prefetching is the act of preloading the code-splitted javascript & data for instant navigation.

Option 1
Create a "src/routes/create_product" folder with the 3 steps as subroutes. And create a __layout.svelte inside the create_product folder to share state and UI.

Option 2
But it that doesn't fit you use-case, you can also implement a simple hash based section using the page store:

<script>
  import { page } from "$app/stores";
</script>

{#if $page.url.hash === "#step2"}
  <a href="#step1">Back to step 1</a>
{:else}
  <a href="#step2">Goto step 2</a>
{/if}

(Requires @sveltejs/kit 1.0.0-next.277 or newer).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related