timhall / svelte-apollo

Svelte integration for Apollo GraphQL
MIT License
944 stars 68 forks source link

Feature Request: Support for Svelte 4 #131

Open Serator opened 1 year ago

Serator commented 1 year ago

Svelte 4 is out now, would love to see it supported. Thanks!

alexyeskin commented 12 months ago

Svelte 4 was released 3 month ago and this package updated more than 1 year ago... What if Svelte 4 will never be supported?

misha-otto commented 12 months ago

You can dump this package and use codegen.ts with the following settings.

import type {CodegenConfig} from '@graphql-codegen/cli'

const config: CodegenConfig = {
  schema: './schema.graphql',
  documents: './src/**/*.graphql',
  generates: {
    './src/lib/graphql/generated.ts': {
      plugins: ['typescript', 'typescript-operations', 'graphql-codegen-svelte-apollo'],
      config: {
        clientPath: '../common/helpers/apollo-client',
      },
    },
  },
}

export default config

Then set the Apollo client to the Svelte context at the top level (+layout.svelte)

<script lang="ts">
  setContext(Symbol('client'), apolloClient)
</script>

And use the created queries in your components

<script lang="ts">
  import {TodosSubscription, AddTodo} from '$lib/graphql/generated'

  $: todos = TodosSubscription({})
  let name = ''

  function addTodo() {
    AddTodo({variables: {name}})
      .then(() => (name = ''))
      .catch((error) => {
        console.error(error)
      })
  }
</script>

<div style="text-align:center">
  <h2>Todoer</h2>

  <form on:submit|preventDefault={addTodo}>
    <input placeholder="new todo" bind:value={name} />
    <button type="submit">Submit</button>
  </form>

  {#if !$todos}
    <p>.. loading</p>
  {:else}
    {#each $todos?.data?.todos ?? [] as todo}
      <p class:done={todo.isDone}>{todo.name}</p>
    {/each}
  {/if}
</div>

full repo with my experiments