### Navigate and Install Dependencies Source: https://houdinigraphql.com/api/react After creating a project, navigate into the directory, install dependencies, and start the development server. ```bash cd && npm i && npm run dev ``` -------------------------------- ### Basic Client Plugin with 'start' Hook Source: https://houdinigraphql.com/api/client-plugins An example of a client plugin using the 'start' hook to log a message and proceed to the next step in the pipeline. Ensure 'next' or 'resolve' is called to prevent the pipeline from hanging. ```typescript import type { ClientPlugin } from '$houdini' const sayHello: ClientPlugin = () => { return { start(ctx, { next }) { // say hello console.log("Hello world!") // move onto the next step in the pipeline next(ctx) } } } ``` ```javascript /** @type { import('$houdini').ClientPlugin } */ const sayHello = () => { return { start(ctx, { next }) { // say hello console.log('Hello world!') // move onto the next step in the pipeline next(ctx) }, } } ``` -------------------------------- ### Set Up Houdini Project Source: https://houdinigraphql.com/intro Use these commands to clone the Houdini intro project and install dependencies. Navigate to the project directory and start the dev server with `npm run dev`. ```bash npx degit houdinigraphql/intro hello-houdini cd hello-houdini npm i ``` -------------------------------- ### houdini init Source: https://houdinigraphql.com/api/command-line Bootstraps a new project with the necessary files to start using Houdini. ```APIDOC ## houdini init ### Description Bootstraps a new project with the necessary files to start using houdini. ### Flags - **--headers / -h** (string) - Optional - Specifies headers to use when pulling your schema (KEY=VALUE). ``` -------------------------------- ### Houdini Client Configuration Source: https://houdinigraphql.com/api/client-plugins/plugins/query Example of how to initialize the HoudiniClient and include the query plugin in the pipeline. ```APIDOC ## Houdini Client Configuration ### Description This configuration demonstrates how to instantiate a new HoudiniClient and register the core `query` plugin within the client pipeline. ### Request Example ```typescript import { HoudiniClient } from '$houdini' import { query } from '$houdini/plugins' export default new HoudiniClient({ url: "...", pipeline: [ query ] }) ``` ``` -------------------------------- ### Install houdini-svelte Source: https://houdinigraphql.com/guides/setting-up-your-project Install the dedicated Svelte package for Houdini. ```bash yarn add -D houdini-svelte # or npm install --save-dev houdini-svelte # or pnpm install --save-dev houdini-svelte ``` -------------------------------- ### Houdini Configuration File Example Source: https://houdinigraphql.com/api/config Defines the structure for the `houdini.config.js` file, including schema URL and custom scalar mappings. ```javascript /** @type {import('houdini').ConfigFile} */ export default { watchSchema: { url: 'http://localhost:4000/graphql', }, scalars: { DateTime: { type: 'Date', unmarshal(val) { return val ? new Date(val) : null }, marshal(date) { return date && date.getTime() } } } } ``` -------------------------------- ### Plugin Setup Hooks Source: https://houdinigraphql.com/api/codegen-plugins Configuration hooks for managing plugin execution order, environment variables, and config modifications. ```APIDOC ## Plugin Setup Hooks ### order - **Type**: "before" | "after" - **Description**: Defines whether the plugin runs before or after core plugins. ### config - **Type**: string - **Description**: Points to a module that exports a function to update the Houdini configuration. ### env - **Type**: ({ env: any; config: Config }) => Promise> - **Description**: Adds environment variables to the Houdini pipeline. ### afterLoad - **Type**: (config: Config) => Promise | void - **Description**: Invoked after all plugins have loaded and modified configuration values. ``` -------------------------------- ### Setup Vite plugin Source: https://houdinigraphql.com/api Integrate Houdini into a Vite project via the configuration file. ```javascript // vite.config.js import houdini from 'houdini/vite' export default { plugins: [houdini(), ...], } ``` ```javascript // vite.config.js import houdini from 'houdini/vite' export default { plugins: [houdini(), ...], } ``` -------------------------------- ### Install Houdini Dependencies Source: https://houdinigraphql.com/guides/setting-up-your-project Install the base houdini package as a development dependency. ```bash yarn add -D houdini # or npm install --save-dev houdini # or pnpm install --save-dev houdini ``` -------------------------------- ### Define a Houdini Client Plugin Source: https://houdinigraphql.com/api/client-plugins Example of defining a client plugin function that returns an object with lifecycle hooks like 'start'. This plugin structure allows for customization of the request pipeline. ```javascript import { plugin } from 'houdini' const sayHello: ClientPlugin = () => { return { start(ctx, { next }) { // ... } } } ``` -------------------------------- ### Define a GraphQL Query Document Source: https://houdinigraphql.com/guides/working-with-graphql Example of a standard GraphQL query definition. ```graphql query ViewerProfile { viewer { firstName } } ``` -------------------------------- ### Install houdini-svelte dependency Source: https://houdinigraphql.com/guides/release-notes Install the required houdini-svelte plugin for version 0.17.0. ```bash npm i --save-dev houdini-svelte ``` -------------------------------- ### Houdini Client with Custom Plugin Source: https://houdinigraphql.com/api/codegen-plugins This example shows how to instantiate `HoudiniClient` with a custom plugin imported from a local path. The configuration value (null in this case) is passed to the plugin's default export. ```typescript import { HoudiniClient } from '$houdini' import customPlugin from 'houdini-plugin-custom/client' export default new HoudiniClient({ plugins: [ customPlugin(null) ] }) ``` -------------------------------- ### Defining GraphQL Schema Source: https://houdinigraphql.com/guides/caching-data Example schema definition for a user-based application. ```graphql type Query { user(name: String!): User users: [User!]! } type User { id: ID! name: String! } ``` -------------------------------- ### Houdini Client Configuration with subscriptions-transport-ws (JavaScript) Source: https://houdinigraphql.com/api/subscription This JavaScript example configures the Houdini client to work with the `subscriptions-transport-ws` protocol. It requires a custom client implementation to bridge the `SubscriptionClient` with Houdini's subscription handler interface. ```javascript import { SubscriptionClient } from 'subscriptions-transport-ws' import { browser } from '$app/environment' import { subscription } from '$houdini/plugins' function createClient() { // instantiate the transport client const client = new SubscriptionClient('ws://api.url', { reconnect: true, }) // wrap the client in something houdini can use return { subscribe(payload, handlers) { // send the request const { unsubscribe } = client.request(payload).subscribe(handlers) // return the function to unsubscribe return unsubscribe }, } } export default new HoudiniClient({ url: '...', plugins: [subscription(createClient)], }) ``` -------------------------------- ### Define a GraphQL Query for a List of Shows Source: https://houdinigraphql.com/api/react Define your application's queries in `.gql` files. Queries must have a unique name. This example defines a query to fetch titles of shows. ```graphql query ShowList { shows { title } } ``` -------------------------------- ### Houdini Client Configuration with graphql-ws (TypeScript) Source: https://houdinigraphql.com/api/subscription Configure the Houdini client to use the `graphql-ws` protocol for subscriptions. This example shows how to create a client using `graphql-ws` and integrate it with Houdini's subscription plugin. ```typescript import { createClient } from 'graphql-ws' import { subscription } from '$houdini/plugins' export default new HoudiniClient({ url: "...", plugins: [ subscription(() => createClient({ url: 'ws://api.url' })) ] }) ``` -------------------------------- ### Configure Houdini Client with URL Source: https://houdinigraphql.com/guides/release-notes Replace the entire fetch function with a single configuration value for the client's URL. This simplifies client setup for basic network requests. ```typescript import { HoudiniClient } from '$houdini' const url = 'my_app.com' export default new HoudiniClient({ url, }) ``` -------------------------------- ### Fragments with Svelte 5 Runes Source: https://houdinigraphql.com/guides/svelte-5 Example of migrating fragments to Svelte 5 syntax using runes. The `fragment` function should be used, and the fragment definition is passed to it. ```typescript

{$data.name} is {$data.age} years old!

``` ```javascript

{$data.name} is {$data.age} years old!

``` -------------------------------- ### Define GraphQL Query in Svelte (TypeScript) Source: https://houdinigraphql.com/guides/architecture Use the `graphql` function to define a query and generate a specific store for it. This is the initial setup for fetching user data. ```svelte {$UserList.data?.users?.map(user => user.name).join(', ')} ``` -------------------------------- ### Inline Query in Route Component (JavaScript) Source: https://houdinigraphql.com/guides/working-with-graphql This JavaScript example demonstrates using an inline query within a SvelteKit route component, utilizing a reactive statement for store definition. It's useful for simple routes where data needs are close to the UI. ```svelte {$info.data.viewer.firstName} ``` -------------------------------- ### Svelte Plugin Configuration Source: https://houdinigraphql.com/api/config Configure the Houdini Svelte plugin by adding it to the `plugins` key in your `houdini.config.js` file. This example shows the basic setup. ```APIDOC ## Svelte Plugin Configuration ### Description Configure the Houdini Svelte plugin by adding it to the `plugins` key in your `houdini.config.js` file. This example shows the basic setup. ### Method Configuration ### Endpoint `houdini.config.js` ### Parameters #### Request Body - **plugins** (object) - Required - An object containing plugin configurations. - **houdini-svelte** (object) - Required - Configuration for the Houdini Svelte plugin. - **client** (string) - Optional, default: `./src/client` - Relative path to the file exporting your Houdini client. - **defaultRouteBlocking** (boolean) - Optional, default: `false` - Default blocking behavior for client-side navigation. - **projectDir** (string) - Optional, default: `process.cwd()` - Absolute path to your SvelteKit project. - **pageQueryFilename** (string) - Optional, default: `"+page.gql"` - Filename for page queries. - **layoutQueryFilename** (string) - Optional, default: `"+layout.gql"` - Filename for layout queries. - **quietQueryErrors** (boolean) - Optional, default: `false` - If true, query errors will not be thrown as exceptions. - **static** (boolean) - Optional, default: `false` - Flag to remove session infrastructure. - **framework** (string) - Optional, default: `undefined` - Override framework detection (`kit` or `svelte`). ### Request Example ```javascript // houdini.config.js /// /** @type {import('houdini').ConfigFile} */ export default { // ... plugins: { 'houdini-svelte': { } } } ``` ``` -------------------------------- ### Initialize Houdini Project Source: https://houdinigraphql.com/guides/setting-up-your-project Run the automated initialization script to configure the project, download the schema, and prepare files. ```bash npx houdini@latest init ``` -------------------------------- ### Create a New Houdini Project Source: https://houdinigraphql.com/api/react Use this command to initialize a new project with Houdini. Follow the prompts to configure your project. ```bash npm create houdini@latest ``` -------------------------------- ### Initialize Houdini Project Source: https://houdinigraphql.com/api/cli Bootstraps a new Houdini project with the necessary files. The `--headers` flag can be used to specify headers for schema pulling during initialization. ```bash houdini init ``` -------------------------------- ### Manual Loading Source: https://houdinigraphql.com/api/query Pattern for manually instantiating stores and fetching data within SvelteKit load functions. ```APIDOC ## Manual Loading ### Description Use the generated `load_` functions to manually fetch data for a route. This provides full control over the loading process. ### Parameters - **event** (PageLoadEvent) - Required - The SvelteKit load event. - **variables** (Object) - Optional - Query variables if required by the store. ``` -------------------------------- ### Get a Record from the Cache Source: https://houdinigraphql.com/api/cache Create a record proxy to interact with entities in Houdini's cache using the 'get' method. Specify the type name and a unique identifier. ```javascript import { cache } from '$houdini' const user = cache.get('User', { id: '1' }) ``` -------------------------------- ### Initialize HoudiniClient Source: https://houdinigraphql.com/api Configure the HoudiniClient with a URL and custom fetch parameters. ```javascript new HoudiniClient({ url: "...", fetchParams({ session }) { return { headers: { } } } }) ``` ```javascript new HoudiniClient({ url: "...", fetchParams({ session }) { return { headers: { } } } }) ``` -------------------------------- ### Subscription Plugin Configuration Source: https://houdinigraphql.com/api/client-plugins/plugins/subscription How to initialize the HoudiniClient with the subscription plugin. ```APIDOC ## Subscription Plugin Configuration ### Description This plugin defines the default behavior for subscriptions in Houdini. It resolves on `start` when not in the browser. ### Type `(handler: SubscriptionHandler) => ClientPlugin` ### Implementation Example ```typescript import { HoudiniClient } from '$houdini' import { subscription } from '$houdini/plugins' export default new HoudiniClient({ url: "...", pipeline: [ subscription ] }) ``` ``` -------------------------------- ### Submit Mutation without ID Source: https://houdinigraphql.com/api/mutation Example of an optimistic response attempt when the ID is unknown. ```javascript CreateTodoItem.mutate( { text: "My Item": }, { optimisticResponse: { createItem: { item: { id: "????" // <--- what goes here? text: "My Item", } } } } ) ``` -------------------------------- ### Fetch GraphQL Query on Mount (JavaScript) Source: https://houdinigraphql.com/guides/architecture This JavaScript version of the transformed Svelte component demonstrates explicit data fetching by creating a `UserListStore` and invoking `fetch()` during component mounting. ```svelte {$UserList.data?.users?.map(user => user.name).join(', ')} ``` -------------------------------- ### Priming Cache with Query Hints Source: https://houdinigraphql.com/guides/caching-data Pre-populate the cache with query results before navigation to ensure data is available immediately. ```javascript // in a loop over users... ``` ```javascript import { cache, graphql } from "$houdini" function primeCache(user) { // prime the cache to know the id of the user we are resolving cache.write({ query: graphql(` query UserProfileHint($name: String!) { user(name: $name) { id } } `), data: { user: { id: user.id, } }, variables: { name: user.name, } }) } // in a loop over users... primeCache(user)}> ``` -------------------------------- ### Generated Svelte Component for Houdini Query Source: https://houdinigraphql.com/guides/faq This is an example of a Svelte component generated by Houdini, which receives query data from the PageData. ```svelte ``` ```svelte ``` -------------------------------- ### Configure Deployment Adapter Source: https://houdinigraphql.com/api/react Pass a deployment adapter to the Houdini vite plugin to prepare the project for specific environments. ```javascript import { sveltekit } from '@sveltejs/kit/vite' import houdini from 'houdini/vite' import adapter from 'houdini-adapter-cloudflare' /** @type {import('vite').UserConfig} */ const config = { plugins: [houdini( { adapter } ), ... ] } export default config ``` -------------------------------- ### Houdini Client Initialization with Mutation Plugin Source: https://houdinigraphql.com/api/client-plugins/plugins/mutation This snippet shows how to initialize the HoudiniClient and include the `mutation` plugin in its pipeline. The `mutation` plugin is essential for handling core mutation behaviors and optimistic responses. ```APIDOC ## Houdini Client Initialization with Mutation Plugin ### Description Initializes the HoudiniClient with a specified URL and includes the `mutation` plugin in the request pipeline. This plugin is responsible for managing mutation operations, including optimistic UI updates. ### Method Client Initialization ### Endpoint N/A (Client-side configuration) ### Parameters #### Configuration Options - **url** (string) - Required - The GraphQL endpoint URL. - **pipeline** (array) - Required - An array of client plugins to be used in the request pipeline. The `mutation` plugin should be included here. ### Request Example ```typescript import { HoudiniClient } from '$houdini' import { mutation } from '$houdini/plugins' export default new HoudiniClient({ url: "YOUR_GRAPHQL_ENDPOINT_URL", pipeline: [ mutation ] }) ``` ### Response N/A (This is a client-side configuration, not an API endpoint response.) ### Error Handling N/A (Configuration errors would typically be caught during build or runtime initialization.) ``` -------------------------------- ### Define GraphQL Query with Route Parameters Source: https://houdinigraphql.com/guides/release-notes Example of a GraphQL query that can infer route parameters automatically without a Variable function. ```graphql query UserInfo($id: Int!) { user(id: $id) { ... } } ``` -------------------------------- ### Define and Use a GraphQL Mutation in React Source: https://houdinigraphql.com/api/react Mutations are defined by wrapping `graphql` with `useMutation`. This example shows a form to submit data using a mutation. ```jsx import { graphql, useMutation } from "$houdini"; export default function EditShow({ AllShows }) { const [one, setOne] = React.useState(""); const [two, setTwo] = React.useState(""); const mutate = useMutation(graphql(` mutation OneTwo($one: String!, $two: String!) { do(one: $one, two: $two) } `)) return (
mutate({one, two})}> setOne(e.target.value)} /> setTwo(e.target.value)} />
) } ``` -------------------------------- ### Create Dynamic Route Directory Source: https://houdinigraphql.com/intro/fetching-data Command to create a directory for a dynamic route using bracket notation. This allows for URL parameters. ```bash cd src/routes && mkdir "[[id]]" && mv +page.* "./[[id]]" ``` -------------------------------- ### Access Query Data in Svelte Component Source: https://houdinigraphql.com/api/query Access the loaded query data within a Svelte component. This example uses TypeScript and imports PageData. ```svelte {$MyProfileInfo.data.viewer.firstName} ``` -------------------------------- ### Configure HoudiniClient with query plugin Source: https://houdinigraphql.com/api/client-plugins/plugins/query Initialize the HoudiniClient by adding the query plugin to the pipeline array. ```typescript import { HoudiniClient } from '$houdini' import { query } from '$houdini/plugins' export default new HoudiniClient({ url: "...", pipeline: [ query ] }) ``` -------------------------------- ### HoudiniClient Constructor Source: https://houdinigraphql.com/api Initializes the Houdini client with the server URL and custom fetch parameters. ```APIDOC ## HoudiniClient Constructor ### Description Initializes a new HoudiniClient instance to manage GraphQL operations and network requests. ### Request Example ```javascript new HoudiniClient({ url: "...", fetchParams({ session }) { return { headers: { } } } }) ``` ``` -------------------------------- ### Enable global query stores Source: https://houdinigraphql.com/guides/release-notes Opt-in to global query store generation in the Houdini configuration. ```javascript export default { plugins: { 'houdini-svelte': {}, 'houdini-plugin-svelte-global-stores': { + generate: 'all', } } } ``` -------------------------------- ### Define a GraphQL Fragment within a useFragment Hook Source: https://houdinigraphql.com/api/react Fragments can be defined directly within the `useFragment` hook. This approach is always compatible. This example defines a fragment for `ShowCardInfo`. ```tsx import { graphql, useFragment } from "$houdini"; export function ShowCard(props: { show: ShowCardInfo }) { const data = useFragment(props.show, graphql(` fragment ShowCardInfo on Show { name } `)) return (
{data.name}
) } ``` -------------------------------- ### Define Page Queries Source: https://houdinigraphql.com/guides/release-notes Use a +page.gql file to automatically opt-into a generated load. ```graphql query MyQuery { viewer { id } } ``` -------------------------------- ### Route Queries with Svelte 5 Runes Source: https://houdinigraphql.com/guides/svelte-5 Example of accessing route query data from PageData in Svelte 5 using runes. Ensure your query store is derived from the PageData. ```typescript

Welcome, {$MyProfile.data?.user.name}!

``` ```javascript

Welcome, {$MyProfile.data?.user.name}!

``` -------------------------------- ### Use External Fragment Stores Source: https://houdinigraphql.com/api/fragment Create fragment stores from external documents using the .get method on the store. ```typescript ``` ```javascript ``` -------------------------------- ### Update List in GraphQL Mutation Source: https://houdinigraphql.com/guides/contributing Use a fragment spread in a mutation to update a list that was previously defined with the @list directive. This example shows how to add a user to the 'All_Users' list. ```graphql mutation AddUserMutation { addUser(firstName: "Alec") { ...All_Users_insert } } ``` -------------------------------- ### Access Query Data in Svelte Component (JavaScript) Source: https://houdinigraphql.com/api/query Access the loaded query data within a Svelte component using plain JavaScript. This example assumes PageData is available. ```svelte {$MyProfileInfo.data.viewer.firstName} ``` -------------------------------- ### Send a Mutation from a Svelte Component Source: https://houdinigraphql.com/api/mutation Use the `graphql` tag to define a mutation and then call the `mutate` method on the returned store to send it to the server. This example shows how to uncheck an item. ```javascript ``` ```javascript ``` -------------------------------- ### Initialize HoudiniClient with fetchParams Source: https://houdinigraphql.com/api/client Configure the client with an API URL and custom fetch parameters for authentication. ```typescript import { HoudiniClient } from '$houdini' export default new HoudiniClient({ url: "http://my.awesome.app.com", fetchParams({ session }) { return { headers: { Authorization: `Bearer ${session.token}` } } } }) ``` ```javascript import { HoudiniClient } from '$houdini' export default new HoudiniClient({ url: 'http://my.awesome.app.com', fetchParams({ session }) { return { headers: { Authorization: `Bearer ${session.token}`, }, } }, }) ``` -------------------------------- ### Enable Link Preloading (Page - Default) Source: https://houdinigraphql.com/api/react The default preloading behavior, `data-houdini-preload` or `data-houdini-preload="page"`, fetches all assets required for the page. ```html
``` -------------------------------- ### Create HoudiniClient Source: https://houdinigraphql.com/guides/setting-up-your-project Initialize the Houdini client with the GraphQL API URL. ```javascript import { HoudiniClient } from '$houdini'; export default new HoudiniClient({ url: 'https://[YOUR_URL_HERE]/graphql' }) ``` -------------------------------- ### Configure houdini.config.js Source: https://houdinigraphql.com/guides/setting-up-your-project Define the base configuration file for Houdini. ```javascript /** @type {import('houdini').ConfigFile} */ const config = { "plugins": { // add your plugins here } } export default config ``` -------------------------------- ### Imperatively Load Next Page in a React Component Source: https://houdinigraphql.com/api/react Use the `$handle` variant of the query prop for imperative tasks like refetching or loading more data. This example shows a button to load the next page. ```tsx export default function ({ ShowList$handle }) { return ( <> {ShowList.shows.map(show => (
{show.title}
))} ) } ``` -------------------------------- ### Access Query Data in a React Component Source: https://houdinigraphql.com/api/react Components can access query data by accepting props with the query name. Ensure props are spread from the argument for static analysis. This example maps over show titles. ```tsx export default function ({ ShowList }) { return ( <> {ShowList.shows.map(show => (
{show.title}
))} ) } ``` -------------------------------- ### Enable Link Preloading (Component) Source: https://houdinigraphql.com/api/react Use `data-houdini-preload="component"` to preload only the page's component source when a user hovers over the link. ```html
``` -------------------------------- ### Houdini Client Configuration with Server-Sent Events (TypeScript) Source: https://houdinigraphql.com/api/subscription Configure the Houdini client to use Server-Sent Events (SSE) for subscriptions. This example demonstrates integrating a client created with `graphql-sse` into the Houdini subscription plugin. ```typescript import { createClient } from 'graphql-sse' import { subscription } from '$houdini/plugins' export default new HoudiniClient({ url: "...", plugins: [ subscription(() => createClient({url: '...'})) ] }) ``` -------------------------------- ### Set Up User Session in hooks.server.js Source: https://houdinigraphql.com/guides/authentication Use this JavaScript version of the server hook in `src/hooks.server.js` to manage user authentication and session data. The `authenticateUser` function needs to be implemented separately. ```javascript import { setSession } from '$houdini' /** @type { import('@sveltejs/kit').Handle } */ export const handle = async ({ event, resolve }) => { // get the user information however you want const user = await authenticateUser(event) // set the session information for this event setSession(event, { user }) // pass the event onto the default handle return await resolve(event) } ``` -------------------------------- ### Configure environment variables with env prefix Source: https://houdinigraphql.com/api/config Use the env: prefix to automatically pull values from .env or .env.local files. ```javascript export default { watchSchema: { url: '...', headers: { Authorization: 'env:AUTH_TOKEN' } } } ``` -------------------------------- ### Page Query Definition Source: https://houdinigraphql.com/guides/working-with-graphql Define a page query in a `+page.gql` file within your route directory. This automatically configures the route to load the specified query, enabling server-side rendering without extra setup. ```graphql query UserInfo { viewer { firstName } } ``` -------------------------------- ### Svelte Component for GraphQL Subscriptions (TypeScript) Source: https://houdinigraphql.com/api/subscription Use this Svelte component to listen for real-time updates from your server. It starts listening automatically when the component mounts in the browser. Ensure you have the necessary imports and that the `itemID` prop is provided. ```svelte latest value: {$updates.data.itemUpdate.item.text} ``` -------------------------------- ### Fetch GraphQL Query on Mount (TypeScript) Source: https://houdinigraphql.com/guides/architecture This transformed Svelte component explicitly instantiates a `UserListStore` and calls `fetch()` within the `onMount` lifecycle function to load data. ```svelte {$UserList.data?.users?.map(user => user.name).join(', ')} ``` -------------------------------- ### Add local plugins Source: https://houdinigraphql.com/api/config Reference local plugins by their relative file path. Local plugins must be written in JavaScript. ```javascript export default { plugins: { './src/plugins/myPlugin.js': {} } } ``` -------------------------------- ### Conditional Rendering for Loading State in Svelte Source: https://houdinigraphql.com/guides/loading-states Use the '$SpeciesInfo.fetching' store value to conditionally render loading UI. This prevents errors when data is null during fetching. The example shows duplicated structure for loading and loaded states. ```svelte {#if $SpeciesInfo.fetching}
{#each Array.from({length: 3}) as _, i }
{/each}
{:else} {species.name} {species.description}
{#each species.evolutionChain as evolvedForm, i }
{node.name}
{/each}
{/if} ``` ```svelte {#if $SpeciesInfo.fetching}
{#each Array.from({length: 3}) as _, i }
{/each}
{:else} {species.name} {species.description}
{#each species.evolutionChain as evolvedForm, i }
{node.name}
{/each}
{/if} ``` -------------------------------- ### Implement Optimistic Response for Mutations Source: https://houdinigraphql.com/guides/caching-data Provide an optimistic response to a mutation to update the cache immediately without waiting for the server response. Ensure an 'id' is always requested and specified for correct cache updates. This example uses Svelte syntax. ```javascript ``` ```javascript ``` -------------------------------- ### Define client plugins Source: https://houdinigraphql.com/api Create custom plugins to intercept and modify the request lifecycle. ```javascript () => ({ start(ctx, { next }) { console.log("hello world") next(ctx) } }) ``` ```javascript () => ({ start(ctx, { next }) { console.log("hello world") next(ctx) } }) ``` -------------------------------- ### Exit Plugin with 'end' Hook for Error Logging Source: https://houdinigraphql.com/api/client-plugins An example of an exit plugin using the 'end' hook to process the final value, logging any errors. Exit hooks must call 'resolve' to ensure data reaches the user and the pipeline completes. ```typescript import type { ClientPlugin } from '$houdini' const logErrors: ClientPlugin = () => { return { end(ctx, { value, resolve }) { // log errors if we see them if (value.errors && value.errors.length > 0) { console.warn('encountered errors:', value.errors) } // keep the information flowing to the user resolve(ctx) } } } ``` ```javascript /** @type { import('$houdini').ClientPlugin } */ const logErrors = () => { return { end(ctx, { value, resolve }) { // log errors if we see them if (value.errors && value.errors.length > 0) { console.warn('encountered errors:', value.errors) } // keep the information flowing to the user resolve(ctx) }, } } ``` -------------------------------- ### Load Fragment Data from External Document (TypeScript) Source: https://houdinigraphql.com/api/fragments Create a fragment store from an external document using the `.get` method on the store. The `user` prop should be of the `UserAvatar` type. ```typescript ``` -------------------------------- ### Client Plugin with 'network' Hook and Resolution Source: https://houdinigraphql.com/api/client-plugins A simplified fetch plugin demonstrating how to use the 'network' hook to perform a fetch request and resolve the pipeline with data. At least one hook must call 'resolve' to provide a value for the store. ```typescript import type { ClientPlugin } from '$houdini' const simpleFetchPlugin: ClientPlugin = () => { return { async network(ctx, { resolve }) { const result = await fetch('...', { body: JSON.stringify({ query: ctx.text }) }) // in reality we need to pass more information here. // see Type Definitions for more information resolve(ctx, { data: result.data }) } } } ``` ```javascript /** @type { import('$houdini').ClientPlugin } */ const simpleFetchPlugin = () => { return { async network(ctx, { resolve }) { const result = await fetch('...', { body: JSON.stringify({ query: ctx.text }), }) // in reality we need to pass more information here. // see Type Definitions for more information resolve(ctx, { data: result.data, }) }, } } ``` -------------------------------- ### Implement Error Handling with Load Hook in SvelteKit (JavaScript) Source: https://houdinigraphql.com/intro/fetching-data Use a `_houdini_beforeLoad` hook in a `+page.js` file to validate route parameters before data loading. This JavaScript version performs the same validation as the TypeScript example, ensuring the Pokémon ID is within the acceptable range. ```javascript import { error } from '@sveltejs/kit' /** * @param { import('./$houdini').BeforeLoadEvent } */ export function _houdini_beforeLoad({ params }) { // if we were given an id, convert the string to a number const id = params.id ? parseInt(params.id) : 1 // check that the id falls between 1 and 151 if (id < 1 || id > 151) { // return a status code 400 along with the error throw error(400, 'id must be between 1 and 151') } } ``` -------------------------------- ### Implement Error Handling with Load Hook in SvelteKit (TypeScript) Source: https://houdinigraphql.com/intro/fetching-data Use a `_houdini_beforeLoad` hook in a `+page.ts` file to validate route parameters before data loading. This example checks if a Pokémon ID is within the valid range (1-151) and throws a SvelteKit error if it's not. ```typescript import { error } from '@sveltejs/kit' import type { BeforeLoadEvent } from './$houdini' export function _houdini_beforeLoad({ params }: BeforeLoadEvent) { // if we were given an id, convert the string to a number const id = params.id ? parseInt(params.id) : 1 // check that the id falls between 1 and 151 if (id < 1 || id > 151) { // return a status code 400 along with the error throw error(400, 'id must be between 1 and 151') } } ``` -------------------------------- ### Update customStores configuration Source: https://houdinigraphql.com/guides/release-notes Merge cursor pagination options into queryCursor and fragmentCursor. ```javascript export default { plugins: { 'houdini-svelte': { 'customStores': { - queryForwardsCursor: 'MyCustomQuery' - queryBackwardsCursor: 'MyCustomQuery' - fragmentForwardsCursor: 'MyCustomFragment' - fragmentBackwardsCursor: 'MyCustomFragment' + queryCursor: 'MyCustomQuery' + fragmentCursor: 'MyCustomFragment', } } } } ``` -------------------------------- ### Configure environment variables with functions Source: https://houdinigraphql.com/api/config Use a function to dynamically process environment variables when direct assignment is insufficient. ```javascript export default { watchSchema: { url: '...', headers: { Authorization(env) { return `Bearer ${env.AUTH_TOKEN}` } } } } ``` -------------------------------- ### Configure SvelteKit Vite Plugin Source: https://houdinigraphql.com/guides/setting-up-your-project Integrate the Houdini Vite plugin into the SvelteKit configuration. ```javascript import { sveltekit } from '@sveltejs/kit/vite' import houdini from 'houdini/vite' /** @type {import('vite').UserConfig} */ const config = { plugins: [houdini(), sveltekit()] } export default config ``` -------------------------------- ### Resetting the Cache Source: https://houdinigraphql.com/api/cache Provides instructions on how to completely reset the cache to an empty state using the `reset` method. ```APIDOC ## Resetting the Cache ### Description Reset the cache to a completely blank state. ### Method `cache.reset() ### Endpoint N/A (Programmatic API) ### Parameters N/A ### Request Example ```javascript import { cache } from '$houdini' cache.reset() ``` ### Response N/A (Mutates cache directly) ``` -------------------------------- ### Houdini Client Configuration with Server-Sent Events (JavaScript) Source: https://houdinigraphql.com/api/subscription This JavaScript configuration enables Houdini subscriptions using Server-Sent Events (SSE). It shows how to use the `graphql-sse` library to create a client and integrate it with Houdini's subscription plugin. ```javascript import { createClient } from 'graphql-sse' import { subscription } from '$houdini/plugins' export default new HoudiniClient({ url: '...', plugins: [subscription(() => createClient({ url: '...' }))], }) ``` -------------------------------- ### Configure .graphqlrc.yaml for Houdini Source: https://houdinigraphql.com/guides/setting-up-your-project Define the schema and document paths in the project root to enable GraphQL IDE features. ```yaml projects: default: schema: - ./schema.graphql - ./$houdini/graphql/schema.graphql documents: - '**/*.gql' - '**/*.svelte' - ./$houdini/graphql/documents.gql ``` -------------------------------- ### Configure plugin settings Source: https://houdinigraphql.com/api/codegen-plugins Define a custom configuration module for your plugin. ```javascript import { plugin } from 'houdini' export default plugin('plugin_name', async () => { return { config: 'plugin_name/config', } }) ``` -------------------------------- ### Enable Link Preloading (Data) Source: https://houdinigraphql.com/api/react Opt-in to preloading link data by adding the `data-houdini-preload="data"` attribute to an anchor tag. This fetches only the page's data. ```html
```