Search code examples
sapper

Preload won't run on component imported to _layout


If I use a preload function in a component at the root of an app, how come it never runs? From https://github.com/sveltejs/sapper-template/issues/94 I take it that this used to be a bug, but was fixed.

So I am having a bit of trouble understanding why this won't run:

_layout.svelte

import someComponent from 'someComponent.svelte';

<someComponent />

someComponent.svelte

<script context="module">
  export async function preload({ params, query }) {
    console.log("i ran")
  }
</script>

Solution

  • As mentioned in the other answer here it seems the preload function is only run on routes. In order to get the the desired effect I could either run a fetch in the onMount function, or pass down the data from the api call from _layout to the desired component. The problem here however is that if you have a nested component structure, it might get quite messy passing down props through several components.