### Install Urql and GraphQL Packages Source: https://nearform.com/open-source/urql/docs/basics/svelte Installs the necessary `@urql/svelte` and `graphql` packages for Svelte applications. `@urql/svelte` provides bindings for Svelte, while `graphql` is a peer dependency for handling GraphQL schemas and operations. This step ensures you have the core libraries needed for GraphQL requests. ```shell yarn add @urql/svelte # or npm install --save @urql/svelte ``` -------------------------------- ### Install Urql Packages Source: https://nearform.com/open-source/urql/docs/basics/react-preact Installs the necessary Urql packages for a project. It includes both the main `urql` package and `@urql/preact` for Preact specific usage. The `graphql` package is also installed as a peer dependency. ```bash yarn add urql # or npm install --save urql ``` ```bash yarn add @urql/preact graphql # or npm install --save @urql/preact graphql ``` -------------------------------- ### Svelte: Pausing and Resuming Queries with queryStore Source: https://nearform.com/open-source/urql/docs/basics/svelte Illustrates how to pause query execution using the `pause` option in `queryStore` and resume it later with the `resume()` method. Useful for pre-conditions. ```svelte ``` -------------------------------- ### Setup Urql Client Source: https://nearform.com/open-source/urql/docs/basics/react-preact Initializes a new Urql Client instance. It requires the GraphQL API endpoint URL and a list of exchanges, such as `cacheExchange` and `fetchExchange`, to manage requests and caching. ```javascript import { Client, cacheExchange, fetchExchange } from 'urql'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], }); ``` -------------------------------- ### Svelte: Setting Request Policy with queryStore Source: https://nearform.com/open-source/urql/docs/basics/svelte Shows how to configure the `requestPolicy` for a query store in Urql Svelte. This controls how results are fetched from the cache and network. ```svelte ... ``` -------------------------------- ### Urql: Default Exchange Setup Source: https://nearform.com/open-source/urql/docs/advanced/authoring-exchanges Presents the default and recommended setup for Urql exchanges, placing the synchronous 'cacheExchange' before the asynchronous 'fetchExchange'. This ordering is crucial for features like suspense mode to function correctly. ```javascript import { Client, cacheExchange, fetchExchange } from 'urql'; new Client({ // ... exchanges: [cacheExchange, fetchExchange]; }); ``` -------------------------------- ### Initialize Urql Client in Svelte Source: https://nearform.com/open-source/urql/docs/basics/svelte Creates a basic Urql `Client` instance in Svelte, specifying the GraphQL API endpoint URL and the necessary exchanges (e.g., `cacheExchange`, `fetchExchange`). This client manages all GraphQL requests and responses for the application. ```javascript import { Client, cacheExchange, fetchExchange } from '@urql/svelte'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], }); ``` -------------------------------- ### Execute a GraphQL Query with queryStore Source: https://nearform.com/open-source/urql/docs/basics/svelte Runs a GraphQL query in Svelte using the `queryStore` function from `@urql/svelte`. It fetches a list of todos, displays loading and error states, and renders the todo titles if the query is successful. The query result is accessed reactively using the `$` prefix. ```javascript {#if $todos.fetching}

Loading...

{:else if $todos.error}

Oh no... {$todos.error.message}

{:else} {/if} ``` -------------------------------- ### Install @urql/core Source: https://nearform.com/open-source/urql/docs/basics/core Instructions for installing the @urql/core package using yarn or npm. This package provides core urql utilities and the Client. ```shell yarn add @urql/core # or npm install --save @urql/core ``` -------------------------------- ### Svelte: Reactive Query with Variables and Pagination Source: https://nearform.com/open-source/urql/docs/basics/svelte Shows how to use a reactive query store with variables for pagination in Urql Svelte. Includes a function to increment the 'from' variable, triggering a new query. ```svelte ``` -------------------------------- ### Install @urql/exchange-auth Source: https://nearform.com/open-source/urql/docs/api/auth-exchange Installs the @urql/exchange-auth package alongside urql using either yarn or npm. ```bash yarn add @urql/exchange-auth # or npm install --save @urql/exchange-auth ``` -------------------------------- ### Install Urql Vue and GraphQL Packages Source: https://nearform.com/open-source/urql/docs/basics/vue Installs the `@urql/vue` library and the `graphql` peer dependency. It's recommended to install both to ensure compatibility and proper functioning of GraphQL-related libraries. ```bash yarn add @urql/vue graphql # or npm install --save @urql/vue graphql ``` -------------------------------- ### Install @urql/exchange-execute Source: https://nearform.com/open-source/urql/docs/api/execute-exchange Installation instructions for the @urql/exchange-execute package using either yarn or npm. This package is required to use the executeExchange. ```bash yarn add @urql/exchange-execute # or npm install --save @urql/exchange-execute ``` -------------------------------- ### Install Urql Persisted Exchange Source: https://nearform.com/open-source/urql/docs/advanced/persistence-and-uploads Installs the `@urql/exchange-persisted` package alongside `urql` for enabling Automatic Persisted Queries. This is a prerequisite for configuring the persisted exchange. ```bash yarn add @urql/exchange-persisted # or npm install --save @urql/exchange-persisted ``` -------------------------------- ### Install Urql for Next.js Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Installs the necessary Urql packages for Next.js integration, including core urql, and Next.js specific bindings. ```bash npm install --save @urql/next urql graphql ``` -------------------------------- ### Install react-ssr-prepass (Bash) Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Command to install the `react-ssr-prepass` package and its peer dependencies (`react-is`, `react-dom`). This package is used to facilitate data fetching during server-side rendering with React. ```bash yarn add react-ssr-prepass react-is react-dom ``` -------------------------------- ### Install SSR Dependencies for React Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Installs the necessary packages for React server-side rendering with Urql, including react-ssr-prepass for data prefetching. ```bash npm install --save react-ssr-prepass react-is react-dom ``` -------------------------------- ### Configure Urql Query Store with Context Options in Svelte Source: https://nearform.com/open-source/urql/docs/basics/svelte This snippet shows how to initialize the queryStore in Svelte, providing client, GraphQL query, and context options like the API URL. The context can override global settings per query. ```html ... ``` -------------------------------- ### Install SSR Dependencies for Preact Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Installs the Preact-compatible drop-in replacement for react-ssr-prepass and Preact itself for server-side rendering. ```bash yarn add preact-ssr-prepass preact # or npm install --save preact-ssr-prepass preact ``` -------------------------------- ### Install next-urql for Legacy Next.js Pages Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Installs the `next-urql` package along with its peer dependencies (`react-is` and `urql`) for use with the older `pages` directory in Next.js. ```bash yarn add next-urql react-is urql graphql ``` -------------------------------- ### JavaScript: Configuring Default Request Policy with Urql Client Source: https://nearform.com/open-source/urql/docs/basics/svelte Demonstrates how to set a default `requestPolicy` for all operations when initializing the Urql `Client` in JavaScript. This overrides the default 'cache-first' policy. ```javascript import { Client, cacheExchange, fetchExchange } from '@urql/svelte'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], // every operation will by default use cache-and-network rather // than cache-first now: requestPolicy: 'cache-and-network', }); ``` -------------------------------- ### Setup Urql Client with Default Retry Options Source: https://nearform.com/open-source/urql/docs/advanced/retry-operations Configures the Urql client by adding the retryExchange. This example shows the default options for retry behavior, including initial delay, maximum delay, random delay, maximum attempts, and the condition for retrying (network errors). The retryExchange should be placed before fetchExchange. ```javascript import { Client, cacheExchange, fetchExchange } from 'urql'; import { retryExchange } from '@urql/exchange-retry'; // None of these options have to be added, these are the default values. const options = { initialDelayMs: 1000, maxDelayMs: 15000, randomDelay: true, maxNumberAttempts: 2, retryIf: err => err && err.networkError, }; // Note the position of the retryExchange - it should be placed prior to the // fetchExchange and after the cacheExchange for it to function correctly const client = new Client({ url: 'http://localhost:1234/graphql', exchanges: [ cacheExchange, retryExchange(options), // Use the retryExchange factory to add a new exchange fetchExchange, ], }); ``` -------------------------------- ### Svelte: Query with Variables using queryStore Source: https://nearform.com/open-source/urql/docs/basics/svelte Demonstrates how to pass variables to a GraphQL query using the `queryStore` in Urql Svelte. The variables are reactive and bound to Svelte's reactivity model. ```svelte ... ``` -------------------------------- ### Provide Urql Client Context in Svelte Source: https://nearform.com/open-source/urql/docs/basics/svelte Sets the Urql `Client` instance as context within a Svelte application using `setContextClient`. This makes the client accessible to child components throughout the application via Svelte's Context API. ```javascript ``` -------------------------------- ### Install next-urql and Dependencies Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Installs the necessary packages for integrating urql with Next.js. This includes `next-urql`, `react-is` (a peer dependency), and `urql` with `graphql` support. ```bash npm install --save next-urql react-is urql graphql ``` -------------------------------- ### Install Urql and Next.js Dependencies Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Installs the @urql/next package and its peer dependencies, urql and graphql, for integrating Urql with Next.js 13 and later. ```bash yarn add @urql/next urql graphql ``` -------------------------------- ### Install populateExchange Package Source: https://nearform.com/open-source/urql/docs/advanced/auto-populate-mutations Installs the `@urql/exchange-populate` package using either yarn or npm. This package provides the `populateExchange` functionality. ```shell yarn add @urql/exchange-populate # or npm install --save @urql/exchange-populate ``` -------------------------------- ### Install urql Refocus Exchange Source: https://nearform.com/open-source/urql/docs/api/refocus-exchange Installs the @urql/exchange-refocus package alongside urql using either yarn or npm package managers. This is the first step before integrating the exchange into your urql client. ```shell yarn add @urql/exchange-refocus # or npm install --save @urql/exchange-refocus ``` -------------------------------- ### Install @urql/exchange-request-policy Source: https://nearform.com/open-source/urql/docs/api/request-policy-exchange Installs the requestPolicyExchange package alongside urql using either Yarn or npm. This is the first step to integrating the exchange into your project. ```shell yarn add @urql/exchange-request-policy # or npm install --save @urql/exchange-request-policy ``` -------------------------------- ### Initialize urql Client with Standard Exchanges Source: https://nearform.com/open-source/urql/docs/advanced/authoring-exchanges Demonstrates initializing a urql Client with essential exchanges: `cacheExchange` for caching results and `fetchExchange` for fetching data from a GraphQL endpoint. The order of exchanges in the list defines the pipeline execution. ```javascript import { Client, fetchExchange, cacheExchange } from 'urql'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], }); ``` -------------------------------- ### Setup executeExchange in Urql Client Source: https://nearform.com/open-source/urql/docs/api/execute-exchange Demonstrates how to add the executeExchange to a urql Client. It typically replaces fetchExchange and should be used last. ```javascript import { createClient, cacheExchange } from 'urql'; import { executeExchange } from '@urql/exchange-execute'; const client = createClient({ url: 'http://localhost:3000/graphql', exchanges: [ cacheExchange, executeExchange({ /* config */ }), ], }); ``` -------------------------------- ### Initialize Urql Client with Exchanges Source: https://nearform.com/open-source/urql/docs/architecture Demonstrates how to create a new Urql Client instance, configuring it with a GraphQL API endpoint and essential exchanges like cacheExchange and fetchExchange. This setup is crucial for enabling caching and network requests for GraphQL operations. ```javascript import { Client, cacheExchange, fetchExchange } from '@urql/core'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], }); ``` -------------------------------- ### Setup Basic Offline Exchange with Graphcache Source: https://nearform.com/open-source/urql/docs/graphcache/offline This snippet demonstrates the initial setup of the offlineExchange from '@urql/exchange-graphcache'. It includes the necessary schema, updates, and optimistic configurations. The client is configured with the offline cache and fetch exchanges. ```javascript import { Client, fetchExchange } from 'urql'; import { offlineExchange } from '@urql/exchange-graphcache'; const cache = offlineExchange({ schema, updates: { /* ... */ }, optimistic: { /* ... */ }, }); const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cache, fetchExchange], }); ``` -------------------------------- ### Install Graphcache with Yarn or npm Source: https://nearform.com/open-source/urql/docs/graphcache This snippet shows how to install the @urql/exchange-graphcache package using either Yarn or npm. This package provides the Graphcache functionality for urql. ```bash yarn add @urql/exchange-graphcache # or npm install --save @urql/exchange-graphcache ``` -------------------------------- ### Programmatic Query Execution with Urql useQuery and setTimeout Source: https://nearform.com/open-source/urql/docs/basics/react-preact Illustrates using reexecuteQuery to trigger a query when the 'pause' option is true. This example sets up a delayed refetch using setTimeout, useful for polling or one-off actions after an initial fetch. ```javascript import { useEffect } from 'react'; import { useQuery } from 'urql'; const Todos = ({ from, limit }) => { const [result, reexecuteQuery] = useQuery({ query: TodosListQuery, variables: { from, limit }, pause: true, }); useEffect(() => { if (result.fetching) return; // Set up to refetch in one second, if the query is idle const timerId = setTimeout(() => { reexecuteQuery({ requestPolicy: 'network-only' }); }, 1000); return () => clearTimeout(timerId); }, [result.fetching, reexecuteQuery]); // ... }; ``` -------------------------------- ### Create Urql Client with Basic Configuration Source: https://nearform.com/open-source/urql/docs/basics/vue Initializes an Urql `Client` instance. Requires a GraphQL API `url` and an array of `exchanges` to manage the request lifecycle. This is the minimal setup for a functional client. ```javascript import { Client, cacheExchange, fetchExchange } from '@urql/vue'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], }); ``` -------------------------------- ### Install @urql/introspection Package Source: https://nearform.com/open-source/urql/docs/graphcache/schema-awareness Instructions for installing the @urql/introspection package using either yarn or npm. This package provides utilities for optimizing GraphQL introspection query results. ```bash yarn add @urql/introspection # or npm install --save @urql/introspection ``` -------------------------------- ### Enable Fetch for Urql Subscriptions Source: https://nearform.com/open-source/urql/docs/advanced/subscriptions This example demonstrates how to enable subscriptions using the standard `fetch` API within Urql. By setting `fetchSubscriptions: true` on the `Client`, Urql will use the `fetchExchange` to handle subscriptions, which is useful for backends like GraphQL Yoga that support this protocol. ```javascript import { Client, cacheExchange, fetchExchange, subscriptionExchange } from 'urql'; const client = new Client({ url: '/graphql', fetchSubscriptions: true, exchanges: [cacheExchange, fetchExchange], }); ``` -------------------------------- ### Setup authExchange with urql Client Source: https://nearform.com/open-source/urql/docs/api/auth-exchange Demonstrates how to add the asynchronous authExchange to a urql client. The authExchange should be placed before fetchExchange but after synchronous exchanges like cacheExchange. ```javascript import { createClient, cacheExchange, fetchExchange } from 'urql'; import { authExchange } from '@urql/exchange-auth'; const client = createClient({ url: 'http://localhost:3000/graphql', exchanges: [ cacheExchange, authExchange(async utils => { return { /* config... */ }; }), fetchExchange, ], }); ``` -------------------------------- ### Install URQL, TypeScript, and GraphQL Code Generator Source: https://nearform.com/open-source/urql/docs/basics/typescript-integration Installs the necessary packages for using URQL with TypeScript and GraphQL Code Generator. Supports both yarn and npm package managers. ```bash yarn add -D graphql typescript @graphql-codegen/cli @graphql-codegen/client-preset # or npm install -D graphql typescript @graphql-codegen/cli @graphql-codegen/client-preset ``` -------------------------------- ### Urql Client Setup with Exchanges for Focus and Stale Time Source: https://nearform.com/open-source/urql/docs/basics/ui-patterns Illustrates how to configure the Urql client by adding exchanges to handle patterns like reacting to focus and stale time. The `refocusExchange` should be added before the `cacheExchange` to ensure proper request handling. ```javascript import { Client, cacheExchange, fetchExchange } from 'urql'; import { refocusExchange } from '@urql/exchange-refocus'; const client = new Client({ url: 'some-url', exchanges: [refocusExchange(), cacheExchange, fetchExchange], }); ``` -------------------------------- ### Install @urql/exchange-retry Source: https://nearform.com/open-source/urql/docs/advanced/retry-operations Installs the retry exchange package for Urql using either yarn or npm. This package is essential for enabling automatic retries of operations. ```bash yarn add @urql/exchange-retry # or npm install --save @urql/exchange-retry ``` -------------------------------- ### Initialize Urql useMutation Hook Source: https://nearform.com/open-source/urql/docs/basics/react-preact Demonstrates the initialization of the useMutation hook from Urql with a predefined mutation string. The hook returns a tuple containing the mutation result and an execute function. ```javascript const UpdateTodo = " mutation ($id: ID!, $title: String!) { updateTodo (id: $id, title: $title) { id title } } "; const Todo = ({ id, title }) => { const [updateTodoResult, updateTodo] = useMutation(UpdateTodo); }; ``` -------------------------------- ### Setup populateExchange in Client Options Source: https://nearform.com/open-source/urql/docs/advanced/auto-populate-mutations Demonstrates how to add the `populateExchange` to the list of exchanges when configuring a urql client. It's recommended to place `populateExchange` before `cacheExchange` for optimal performance and functionality, especially with Graphcache. ```javascript import { Client, fetchExchange } from '@urql/core'; import { populateExchange } from '@urql/exchange-populate'; const client = new Client({ // ... exchanges: [populateExchange({ schema }), cacheExchange, fetchExchange], }); ``` -------------------------------- ### Execute GraphQL Query with urql Client Source: https://nearform.com/open-source/urql/docs/architecture Demonstrates how to execute a GraphQL query using the urql Client and subscribe to its results. This example uses the gql tag for query definition and shows how to pass variables. The subscribe callback receives the query result. ```javascript import { gql } from '@urql/core'; const QUERY = gql` query Test($id: ID!) { getUser(id: $id) { id name } } `; client.query(QUERY, { id: 'test' }).subscribe(result => { console.log(result); // { data: ... } }); ``` -------------------------------- ### Configure Urql with Persisted Exchange Source: https://nearform.com/open-source/urql/docs/advanced/persistence-and-uploads Sets up the Urql client with the `persistedExchange` to enable Automatic Persisted Queries. It includes cache and fetch exchanges, and configures `persistedExchange` to prefer GET requests for persisted queries. ```javascript import { Client, fetchExchange, cacheExchange } from 'urql'; import { persistedExchange } from '@urql/exchange-persisted'; const client = new Client({ url: 'http://localhost:1234/graphql', exchanges: [ cacheExchange, persistedExchange({ preferGetForPersistedQueries: true, }), fetchExchange, ], }); ``` -------------------------------- ### GraphQL Query and Mutation Examples Source: https://nearform.com/open-source/urql/docs/graphcache/normalized-caching Demonstrates a basic GraphQL schema with a query to fetch a list of todos and a mutation to add a new todo. These are foundational for understanding cache update scenarios. ```graphql query TodosList { todos { id title } } mutation AddTodo($title: String!) { addTodo(title: $title) { id title } } ``` -------------------------------- ### Configure Urql useQuery with Context Options Source: https://nearform.com/open-source/urql/docs/basics/react-preact Demonstrates how to configure the useQuery hook with context options like requestPolicy and url. These options can be set globally on the client or per query. ```javascript import { useMemo } from 'react'; import { useQuery } from 'urql'; const Todos = ({ from, limit }) => { const [result, reexecuteQuery] = useQuery({ query: TodosListQuery, variables: { from, limit }, context: useMemo( () => ({ requestPolicy: 'cache-and-network', url: 'http://localhost:3000/graphql?debug=true', }), [] ), }); // ... }; ``` -------------------------------- ### Integrate Schema into urql CacheExchange Source: https://nearform.com/open-source/urql/docs/graphcache/schema-awareness Example of loading a local schema.json file and passing it to the schema option of urql's cacheExchange. This demonstrates how to integrate a pre-fetched and potentially optimized schema into your urql client configuration. ```javascript import schema from './schema.json'; const cache = cacheExchange({ schema }); ``` -------------------------------- ### Example of a Resolver Function in Graphcache Source: https://nearform.com/open-source/urql/docs/api/graphcache Demonstrates how to implement a resolver function for the 'createdAt' field of a 'Todo' type. This example shows how to read existing cache data and transform it, in this case, by creating a Date object. ```javascript { Todo: { createdAt(parent, args, cache) { // Read `createdAt` on the parent but return a Date instance const date = cache.resolve(parent, 'createdAt'); return new Date(date); } } } ``` -------------------------------- ### Provide Urql Client to React/Preact App Source: https://nearform.com/open-source/urql/docs/basics/react-preact Integrates the configured Urql Client into a React or Preact application using the Context API. The `Provider` component wraps the application's routes, making the client accessible to all child components. ```javascript import { Client, Provider, cacheExchange, fetchExchange } from 'urql'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange, fetchExchange], }); const App = () => ( ); ``` -------------------------------- ### Setup requestPolicyExchange in urql Client Source: https://nearform.com/open-source/urql/docs/api/request-policy-exchange Demonstrates how to add the requestPolicyExchange to your urql Client configuration. It should be placed before cacheExchange and any asynchronous exchanges like fetchExchange for optimal functionality. ```javascript import { createClient, cacheExchange, fetchExchange } from 'urql'; import { requestPolicyExchange } from '@urql/exchange-request-policy'; const client = createClient({ url: 'http://localhost:3000/graphql', exchanges: [ requestPolicyExchange({ /* config */ }), cacheExchange, fetchExchange, ], }); ``` -------------------------------- ### GraphQL Queries for Alias Example Source: https://nearform.com/open-source/urql/docs/advanced/auto-populate-mutations Presents two GraphQL queries demonstrating a scenario where aliases are necessary when using `populateExchange` with queries that have different arguments for the same field. This is to avoid merging conflicts. ```graphql # Query 1 { firstTodos: todos(first: 10) { id name } } # Query 2 { lastTodos: todos(last: 20) { id createdAt } } ``` -------------------------------- ### Test Query Execution Skipping Source: https://nearform.com/open-source/urql/docs/advanced/testing This example shows how to test if a query is correctly skipped. By mounting the component within the urql Provider with a mock client, we can then assert that the `executeQuery` method on the mock client was not called, indicating that the query was skipped as intended. ```javascript import { mount } from 'enzyme'; import { Provider } from 'urql'; import { MyComponent } from './MyComponent'; it('skips the query', () => { mount( ); expect(mockClient.executeQuery).toBeCalledTimes(0); }); ``` -------------------------------- ### Re-execute Urql Query with Network Policy in Svelte Source: https://nearform.com/open-source/urql/docs/basics/svelte Demonstrates how to re-execute an Urql query in Svelte using the `reexecute` method on the query store, specifically setting the `requestPolicy` to 'network-only' to bypass the cache. ```html ``` -------------------------------- ### Initialize urql Client with a Custom Error Handling Exchange Source: https://nearform.com/open-source/urql/docs/advanced/authoring-exchanges Shows how to initialize a urql Client with `cacheExchange`, `fetchExchange`, and an additional `mapExchange` for handling errors. The `mapExchange` allows defining a callback (e.g., `onError`) to react to `CombinedError` instances in operation results. ```javascript import { Client, fetchExchange, cacheExchange, mapExchange } from 'urql'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [ cacheExchange, mapExchange({ onError(error) { console.error(error); }, }), fetchExchange, ], }); ``` -------------------------------- ### Handle Urql Mutation Errors in Svelte Source: https://nearform.com/open-source/urql/docs/basics/svelte Shows how to handle potential errors from an Urql mutation in Svelte. Instead of rejecting, the mutation promise resolves to an operation result; errors are checked via `result.error` and logged if present. ```javascript mutateTodo({ id, title: newTitle }).then(result => { if (result.error) { console.error('Oh no!', result.error); } }); ``` -------------------------------- ### Urql: Avoiding Operation Drops with Proper Forwarding Source: https://nearform.com/open-source/urql/docs/advanced/authoring-exchanges Illustrates two approaches to handling operations within an exchange. The first shows an incorrect way to filter operations, potentially dropping unknown types. The second demonstrates the correct method by explicitly forwarding operations that are not handled by the current exchange, ensuring all operation types are processed. ```javascript import { pipe, filter, merge } from 'wonka'; // DON'T: drop unknown operations ({ forward }) => operations$ => { // This doesn't handle operations that aren't queries const queries = pipe( operations$, filter(op => op.kind === 'query') ); return forward(queries); }; // DO: forward operations that you don't handle ({ forward }) => operations$ => { const queries = pipe( operations$, filter(op => op.kind === 'query') ); const rest = pipe( operations$, filter(op => op.kind !== 'query') ); return forward(merge([queries, rest])); }; ``` -------------------------------- ### Configure Vite for Urql Source: https://nearform.com/open-source/urql/docs/basics/svelte Excludes `@urql/svelte` from Vite's dependency pre-bundling to resolve the 'Function called outside component initialization' error. This configuration ensures that Vite correctly processes the Svelte-specific `@urql/svelte` package during development. ```javascript { optimizeDeps: { exclude: ['@urql/svelte'], } // other properties } ``` -------------------------------- ### Vue Suspense: Chaining Urql Queries with useClientHandle Source: https://nearform.com/open-source/urql/docs/basics/vue Illustrates how to use `useClientHandle` in Vue 3's `async setup()` to access the Urql client after an `await` call, enabling chained queries or operations that require client context even outside the initial synchronous scope. ```vue import { gql, useClientHandle } from '@urql/vue'; export default { async setup() { const handle = useClientHandle(); await Promise.resolve(); // NOTE: This could be any await call const result = await handle.useQuery({ query: gql` { todos { id title } } `, }); return { data: result.data }; }, }; ``` -------------------------------- ### Vue Suspense with Urql useQuery Source: https://nearform.com/open-source/urql/docs/basics/vue Demonstrates how to use Urql's `useQuery` within Vue 3's `async setup()` to leverage the Suspense feature for automatic loading state management. The component suspends until data is fetched, and a parent's fallback template is shown. ```vue ``` ```vue ``` -------------------------------- ### Simulate Success Response State with Wonka's 'fromValue' Source: https://nearform.com/open-source/urql/docs/advanced/testing Illustrates how to simulate a successful data response from the server for testing purposes. This is done by providing a mock `executeQuery` function that returns a stream created with Wonka's `fromValue`, emitting the desired data. The example includes a snapshot test to verify the rendered output. ```javascript import { mount } from 'enzyme'; import { Provider } from 'urql'; import { fromValue } from 'wonka'; import { MyComponent } from './MyComponent'; it('matches snapshot', () => { const responseState = { executeQuery: () => fromValue({ data: { posts: [ { id: 1, title: 'Post title', content: 'This is a post' }, { id: 3, title: 'Final post', content: 'Final post here' }, ], }, }), }; const wrapper = mount( ); expect(wrapper).toMatchSnapshot(); }); ``` -------------------------------- ### Send Urql Mutation with Variables in Svelte Source: https://nearform.com/open-source/urql/docs/basics/svelte This Svelte snippet illustrates how to send a GraphQL mutation using Urql's mutationStore. It defines a mutation to update a todo item and accepts `id` and `title` as variables, triggering the mutation within a function. ```html ``` -------------------------------- ### Basic urql No-Operation Exchange Template Source: https://nearform.com/open-source/urql/docs/advanced/authoring-exchanges Provides a basic template for a urql exchange that performs no operations, often referred to as a no-operation or `noopExchange`. It demonstrates the fundamental structure of an exchange, including receiving `client` and `forward` and returning an `ExchangeIO` function that forwards operations and returns results. ```javascript const noopExchange = ({ client, forward }) => { return operations$ => { // <-- The ExchangeIO function const operationResult$ = forward(operations$); return operationResult$; }; }; ``` -------------------------------- ### Run a GraphQL Query with useQuery Hook Source: https://nearform.com/open-source/urql/docs/basics/react-preact Fetches data from a GraphQL API using the `useQuery` hook in a React or Preact component. It handles loading states, displays data, and manages potential errors. The hook accepts a query definition and returns the query result and a re-execution function. ```javascript import { gql, useQuery } from 'urql'; const TodosQuery = gql` query { todos { id title } } `; const Todos = () => { const [result, reexecuteQuery] = useQuery({ query: TodosQuery, }); const { data, fetching, error } = result; if (fetching) return

Loading...

; if (error) return

Oh no... {error.message}

; return ( ); }; ``` -------------------------------- ### Forcefully Re-execute Urql Query with Network Policy Source: https://nearform.com/open-source/urql/docs/basics/react-preact Shows how to programmatically trigger a new query execution using the reexecuteQuery function returned by useQuery. This example specifically overrides the requestPolicy to 'network-only' to bypass the cache for a refresh. ```javascript const Todos = ({ from, limit }) => { const [result, reexecuteQuery] = useQuery({ query: TodosListQuery, variables: { from, limit }, }); const refresh = () => { // Refetch the query and skip the cache reexecuteQuery({ requestPolicy: 'network-only' }); }; }; ``` -------------------------------- ### Client Configuration Source: https://nearform.com/open-source/urql/docs/api/core The Client manages all operations and ongoing requests to the exchange pipeline. It accepts several options on creation. `createClient()` is a convenient alternative to calling `new Client()`. ```APIDOC ## Client Configuration ### Description Configuration options for the urql Client. ### Method `createClient(options)` or `new Client(options)` ### Parameters #### Request Body - **exchanges** (Exchange[]) - Required - An array of `Exchange`s that the client should use. - **url** (string) - Required - The GraphQL API URL as used by `fetchExchange`. - **fetchOptions** (RequestInit | () => RequestInit) - Optional - Additional `fetchOptions` that `fetch` in `fetchExchange` should use to make a request. - **fetch** (typeof fetch) - Optional - An alternative implementation of `fetch` that will be used by the `fetchExchange` instead of `window.fetch`. - **suspense** (?boolean) - Optional - Activates the experimental React suspense mode, which can be used during server-side rendering to prefetch data. - **requestPolicy** (?RequestPolicy) - Optional - Changes the default request policy that will be used. By default, this will be `cache-first`. - **preferGetMethod** (?boolean | 'force' | 'within-url-limit') - Optional - This is picked up by the `fetchExchange` and will force all queries (not mutations) to be sent using the HTTP GET method instead of POST if the length of the resulting URL doesn't exceed 2048 characters. When `'force'` is passed a GET request is always sent regardless of how long the resulting URL is. ### Request Example ```json { "exchanges": [ // exchange configurations ], "url": "/graphql", "requestPolicy": "network-only" } ``` ### Response #### Success Response (200) - **Client** - The created urql client instance. #### Response Example ```json { "client": "{...}" } ``` ``` -------------------------------- ### Initialize urql Client with Graphcache Source: https://nearform.com/open-source/urql/docs/graphcache This code demonstrates how to set up a urql client, replacing the default cacheExchange with the Graphcache's cacheExchange. It imports necessary components and configures the client to use Graphcache for normalized caching. ```javascript import { Client, fetchExchange } from 'urql'; import { cacheExchange } from '@urql/exchange-graphcache'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [cacheExchange({}), fetchExchange], }); ``` -------------------------------- ### Initialize SSR Exchange in urql Client (JavaScript) Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Demonstrates initializing the ssrExchange with urql's Client for server-side rendering. It configures the exchange to detect the environment (server/client) and optionally uses initial state for hydration. ```javascript import { Client, cacheExchange, fetchExchange, ssrExchange } from '@urql/core'; const isServerSide = typeof window === 'undefined'; // The `ssrExchange` must be initialized with `isClient` and `initialState` const ssr = ssrExchange({ isClient: !isServerSide, initialState: !isServerSide ? window.__URQL_DATA__ : undefined, }); const client = new Client({ exchanges: [ cacheExchange, ssr, // Add `ssr` in front of the `fetchExchange` fetchExchange, ], }); ``` -------------------------------- ### Configure urql Client with authExchange Source: https://nearform.com/open-source/urql/docs/advanced/authentication Sets up a urql client by integrating the authExchange. The authExchange should be placed after synchronous exchanges like cacheExchange but before network exchanges like fetchExchange. It requires an asynchronous initialization function that returns configuration options. ```javascript import { Client, cacheExchange, fetchExchange } from 'urql'; import { authExchange } from '@urql/exchange-auth'; const client = new Client({ url: 'http://localhost:3000/graphql', exchanges: [ cacheExchange, authExchange(async utils => { return { /* config... */ }; }), fetchExchange, ], }); ``` -------------------------------- ### Context API Source: https://nearform.com/open-source/urql/docs/api/svelte Urql's Svelte bindings provide utilities to manage the `Client` instance using Svelte's Context API, offering convenience over manual passing. ```APIDOC ## Context API ### Description In `urql`'s Svelte bindings, the `Client` is passed into the factories for stores above manually. For convenience, instead of keeping a `Client` singleton, we may also use Svelte's Context API. `@urql/svelte` provides wrapper functions around Svelte's `setContext` and `getContext` functions. ### Utilities - **setContextClient(client: Client)**: Sets the Urql client in the Svelte context. - **getContextClient()**: Retrieves the Urql client from the Svelte context. - **initContextClient(options: ClientOptions): Client**: A shortcut for `createClient` + `setContextClient`. ### Example Usage ```javascript // In your root component (e.g., App.svelte or main.js) import { setContextClient } from '@urql/svelte'; import { createClient } from '@urql/core'; const client = createClient({ url: '/graphql' }); setContextClient(client); // Or using initContextClient: // import { initContextClient } from '@urql/svelte'; // initContextClient({ url: '/graphql' }); // In a child component: import { getContextClient } from '@urql/svelte'; const client = getContextClient(); // Now you can use the client for stores, e.g.: import { queryStore } from '@urql/svelte'; const todos = queryStore({ client, query: '{ todos { id } }' }); ``` ``` -------------------------------- ### GraphQL Query Document Example Source: https://nearform.com/open-source/urql/docs/graphcache/normalized-caching An example of a GraphQL query document used to fetch data. This structure defines the shape of the data to be retrieved from the API, including nested relationships between types. ```graphql { __typename todo(id: 1) { __typename id title author { __typename id name } } } ``` -------------------------------- ### Svelte: Implement Real-time Message Subscription with subscriptionStore Source: https://nearform.com/open-source/urql/docs/advanced/subscriptions Shows how to use the `subscriptionStore` function from '@urql/svelte' to subscribe to new messages in Svelte. It displays a list of incoming messages, updating dynamically. Requires '@urql/svelte'. ```svelte {#if !$messages.data}

No new messages

{:else} {/if} ``` -------------------------------- ### Corresponding JSON Result Example Source: https://nearform.com/open-source/urql/docs/graphcache/normalized-caching The JSON data structure returned by a GraphQL API in response to a query. This example demonstrates how the data is nested and includes __typename fields, which are crucial for normalized caching. ```json { "__typename": "Query", "todo": { "__typename": "Todo", "id": 1, "title": "implement graphcache", "author": { "__typename": "Author", "id": 1, "name": "urql-team" } } } ``` -------------------------------- ### Provide Urql Client using provideClient Function Source: https://nearform.com/open-source/urql/docs/basics/vue Sets up the Urql `Client` for use within a Vue application using the `provideClient` function. This method makes the client available to all child components that need to interact with the GraphQL API. ```javascript ``` -------------------------------- ### Get Entity Key with Urql Cache Source: https://nearform.com/open-source/urql/docs/api/graphcache Demonstrates how to use `cache.keyOfEntity` to get a unique key for a given entity object. This method considers the `__typename`, `id` (or `_id`), and custom `keys` configuration. It returns `null` if the entity is not keyable. ```javascript cache.keyOfEntity({ __typename: 'Todo', id: 1 }); // 'Todo:1' cache.keyOfEntity({ __typename: 'Query' }); // 'Query' cache.keyOfEntity({ __typename: 'Unknown' }); // null ``` -------------------------------- ### client.executeSubscription Source: https://nearform.com/open-source/urql/docs/api/core Functionally the same as `client.executeQuery`, but creates operations for subscriptions with `kind` set to `'subscription'`. ```APIDOC ## client.executeSubscription ### Description Executes a GraphQL subscription and returns a stream of results. ### Method `client.executeSubscription(request, operationContext)` ### Endpoint N/A (Method on Client instance) ### Parameters #### Request Body - **request** (GraphQLRequest) - Required - The GraphQL request object. - **operationContext** (Partial) - Optional - Additional context for the operation. ### Request Example ```json { "query": "subscription { newTodo { id name } }" } ``` ### Response #### Success Response (200) - **Source** - A stream of operation results. #### Response Example ```json { "data": { "newTodo": { "id": 2, "name": "Build something cool" } } } ``` ``` -------------------------------- ### Basic Page Integration with withUrqlClient (React/JSX) Source: https://nearform.com/open-source/urql/docs/advanced/server-side-rendering Demonstrates wrapping a Next.js page component with `withUrqlClient` to provide urql context. It shows basic query usage and client configuration. ```javascript import React from 'react'; import { useQuery } from 'urql'; import { withUrqlClient } from 'next-urql'; const Index = () => { const [result] = useQuery({ query: '{ test }', }); // ... }; export default withUrqlClient((_ssrExchange, ctx) => ({ // ...add your Client options here url: 'http://localhost:3000/graphql', }))(Index); ``` -------------------------------- ### Define GraphQL Query as String Source: https://nearform.com/open-source/urql/docs/basics/core Example of defining a GraphQL query as a simple string variable. This is a basic way to represent GraphQL operations. ```javascript const TodosQuery = ` query { todos { id title } } `; ```