Svelte

Store Integration

Curi relies on Svelte's store to interface with an application. By adding the response (plus the router and navigation objects) to the store, they are accessible throughout the application.

@curi/svelte provides a function to link the router to the store. This sets up an observer, so that whenever there is a new response, the parts of your application that use the response will be re-rendered.

import store from "svelte/store";
import { curiStore } from "@curi/svelte";

import router from "./router";

const store = new Store();
curiStore(router, store);

Rendering with the response

Svelte allows you to render dynamic components using the <svelte:component this> syntax. If you set Svelte components as the body properties on your responses, you can combine <svelte:component this> and response.body to render the appropriate component for a response.

A root component is a good place to perform general application layout, like menus, in addition to rendering the response's body.

<template>
  <header>
    <NavLinks />
  </header>
  <main>
    <svelte:component this={$curi.response.body} />
  </main>
</template>

<script>
  import NavLinks from "./NavLinks";
  export default {
    components: { NavLinks }
  };
</script>

If your routes use an object to attach multiple components to a response, splitting them apart in computed properties may give your templates a cleaner look.

If you do attach multiple components to a response, please remember that you want every route to set the same body shape. Otherwise, you'll have to determine the shape and change how you render, which can quickly become messy.

<script>
const routes = prepareRoutes([
  {
    name: "Home",
    path: "",
    response() {
      return {
        body: {
          main: HomeMain,
          menu: HomeMenu
        }
      }
    }
  },
  // ...
]);
</script>

<template>
  <header>
    <svelte:component this={menu} />
  </header>
  <main>
  <svelte:component this={main} />
  </main>
</template>

<script>
  export default {
    computed: {
      main({ $curi }) {
        return $curi.response.body.main;
      },
      menu({ $curi }) {
        return $curi.response.body.menu;
      }
    }
  }
</script>

Please check out the full @curi/svelte API documentation to see every component that the package provides.