Search code examples
javascriptsveltesappersvelte-3svelte-component

Use JS label syntax "$:" without "Cannot access <obj> before initialization" error


I'm using this code in my Svelte app:

<script>
  import { query } from '@urql/svelte'

  import { MY_QUERY } from 'queries'

  $: myQuery = query({
    query: MY_QUERY,
    variables: { id }
  })
</script>

{#if !$myQuery}
  Loading...
{:else}
  Oh WOW! {$myQuery.data}
{/if}

Trying the same code in Sapper I get this error:

Cannot access 'myQuery' before initialization.

If I change the below line

  • from this: $: myQuery = query({

  • to this: const myQuery = query({

it works!

Why?


Solution

  • Since this is Sapper code, and I don't see anything else obvious, I think you've run fool this this bug. The error only happens on the server-side (SSR), doesn't it?

    Then the workaround is to hint the compiler into declaring the variable in the right place:

      let myQuery // <=== add this
    
      $: myQuery = query({
        query: MY_QUERY,
        variables: { id }
      })