Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Preload changes #554

Closed
Rich-Harris opened this issue Feb 1, 2019 · 2 comments
Closed

Preload changes #554

Rich-Harris opened this issue Feb 1, 2019 · 2 comments

Comments

@Rich-Harris
Copy link
Member

A consequence of the Svelte 3 way of doing things is that we can't pass around this.store to preload functions. Instead, I think it could look like this:

<script context="module">
  export function preload(page, session) {
    const { params, query, page } = page; // no different from before

    // session is just whatever was generated from the `req` object
    // — the value of the store returned from `app.getSession()`
    if (!session.user) {
      return this.redirect(302, 'login');
    }

    return fetch(`foo/${page.params.whatever}.json`).then(r => r.json());
  }
</script>

This is an opportunity to fix a bug: if you're on a page that redirects to a login page if there's no user object, or otherwise preloads data specific to that user, then logging out won't automatically update the page — you could easily end up with a page like

HOME   ABOUT                                                                      LOG IN
-----------------------------------------------------------------------------------------

Secret, user-specific data that shouldn't be visible alongside a 'log in' button:

* foo
* bar
* baz

With this change, we can re-run preload when the session store changes, e.g. as a result of something like this in a nav bar:

<script>
  import { getSession } from 'app';

  const session = getSession();

  function logout() {
    session.update(session => Object.assign({}, session, { user: null }));
  }
</script>

{#if $session.user}
  <p>hello {$session.user.name}! <button on:click={logout}>log out</button></p>
{:else}
  <a href="login">log in</a>
{/if}

We'd only need to rerun preload functions when session changed if the function's arity was 2. (A related thought: we need to rerun all preload functions when query changes, including for intermediate layout components. But maybe if the object passed in had getters or was a proxy, we could check to see whether query was used, and skip unnecessary preloads to avoid overfetching where possible. But that's a low priority nice-to-have.)

Thoughts?

@Rich-Harris
Copy link
Member Author

Implemented on master, except for the arity check optimisation. Will add a new issue for that

@antony
Copy link
Member

antony commented Feb 7, 2019

I have a feeling that this functionality is scuppered by #415 - since my browser caches the page for 10 minutes, meaning that the page is never hit and thus the preload is never run, regardless of whether session has been changed or not.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants