Svelte custom store for going back and forward between components

303 Views Asked by At

I'm doing a SPA in Svelte and would like to know if is possible to create a custom store for going back and forward between components.

This is a working example where I use an array of string to show the approach. https://svelte.dev/repl/1f9e72105e8d45e0bd6df61b304fd257?version=3.31.0

import { writable } from 'svelte/store'

function create_navigation() {
  const screens = ['Step 1', 'Step 2', 'Step 3', 'Step 4', 'Step 5']
  const { subscribe, set } = writable(screens[0])
  let n = 0
  
  return {
    subscribe,
    next: () => (n < screens.length - 1 && n++, set(screens[n])),
    prev: () => (n > 0 && n--, set(screens[n])),
    reset: () => set(screens[0])
    }
}

export const screen = create_navigation()

If we import some components into my store and create an array of components, it will not render. Probably I'm missing some concepts so any help will be really appreciate : )

Right now, to solve this I work with numbers in my store and then in App.svelte I set my array of components.

1

There are 1 best solutions below

1
On BEST ANSWER

You can create an array of components, instead of an array of strings, like:

import { writable } from 'svelte/store'
import Screen1 from './Screen1.svelte'
import Screen2 from './Screen2.svelte'

function create_navigation() {
  const screens = [Screen1, Screen2]
.
.
.

and use <svelte:component this={$screen}/> in your App.svelte component.

Example: https://svelte.dev/repl/5752ba81b6c94b80b31131c02431e8ac?version=3.31.0