Skip to content

Async data #654

@Rich-Harris

Description

@Rich-Harris

Been refactoring https://svelte.technology — inching towards a more declarative/universal way of handling routing etc.

One thing that stands out is that there's really no good way for components to declare their own data dependencies in a universal way. So you have to have a dedicated handler per route, in case you need to do something like fetch a blog post's JSON.

It would be nice if that stuff could sit in the component itself. You'd still have to handle data fetching differently between server and client, but at least you'd be able to declare all your routes declaratively (up to a point, anyway).

Maybe something like this:

<script>
  export default {
    preload (params) {
      if (isServer) { // TODO figure out what this actually looks like...
        return require(`../public/blog-posts/${params.slug}.json`);
      } else {
        return fetch(`/blog-posts/${params.slug}.json`).then(r => r.json());
      }
    },

    data (preloaded) {
      return {
        post: preloaded
      };
    }
  };
</script>

This only really works for top-level components — it could get pretty crazy if you had something like this:

{{#if foo}}
  <ComponentThatPreloadsStuff/>
{{/if}}

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions