···11+---
22+'@urql/core': patch
33+---
44+55+Add missing type exports of SSR-related types (`SerializedResult`, `SSRExchangeParams`, `SSRExchange`, and `SSRData`) to `@urql/core`'s type exports.
···77 getIntrospectionQuery,
88} from 'graphql';
991010+/** Returns an {@link IntrospectionQuery} result for a given GraphQL schema.
1111+ *
1212+ * @param input - A GraphQL schema, either as an SDL string, or a {@link GraphQLSchema} object.
1313+ * @returns an {@link IntrospectionQuery} result.
1414+ *
1515+ * @remarks
1616+ * `getIntrospectedSchema` can be used to get a Schema Introspection result from
1717+ * a given GraphQL schema. The schema can be passed as an SDL string or a
1818+ * {@link GraphQLSchema} object. If an {@link IntrospectionQuery} object is
1919+ * passed, it'll be passed through.
2020+ *
2121+ * @throws
2222+ * If `input` cannot be parsed or converted into a {@link GraphQLSchema} then
2323+ * a {@link TypeError} will be thrown.
2424+ */
1025export const getIntrospectedSchema = (
1126 input: string | IntrospectionQuery | GraphQLSchema
1227): IntrospectionQuery => {
···156156 }
157157};
158158159159+/** Input parameters for the {@link minifyIntrospectionQuery} function. */
159160export interface MinifySchemaOptions {
160160- /** Includes scalar names (instead of an `Any` replacement) in the output when enabled. */
161161+ /** Includes scalars instead of removing them.
162162+ *
163163+ * @remarks
164164+ * By default, all scalars will be replaced by a single scalar called `Any`
165165+ * in the output, unless this option is set to `true`.
166166+ */
161167 includeScalars?: boolean;
162162- /** Includes enums (instead of an `Any` replacement) in the output when enabled. */
168168+ /** Includes enums instead of removing them.
169169+ *
170170+ * @remarks
171171+ * By default, all enums will be replaced by a single scalar called `Any`
172172+ * in the output, unless this option is set to `true`.
173173+ */
163174 includeEnums?: boolean;
164164- /** Includes all input objects (instead of an `Any` replacement) in the output when enabled. */
175175+ /** Includes inputs instead of removing them.
176176+ *
177177+ * @remarks
178178+ * By default, all inputs will be replaced by a single scalar called `Any`
179179+ * in the output, unless this option is set to `true`.
180180+ */
165181 includeInputs?: boolean;
166166- /** Includes all directives in the output when enabled. */
182182+ /** Includes directives instead of removing them. */
167183 includeDirectives?: boolean;
168184}
169185170170-/** Removes extraneous information from introspected schema data to minify it and prepare it for use on the client-side. */
186186+/** Minifies an {@link IntrospectionQuery} for use with Graphcache or the `populateExchange`.
187187+ *
188188+ * @param schema - An {@link IntrospectionQuery} object to be minified.
189189+ * @param opts - An optional {@link MinifySchemaOptions} configuration object.
190190+ * @returns the minified {@link IntrospectionQuery} object.
191191+ *
192192+ * @remarks
193193+ * `minifyIntrospectionQuery` reduces the size of an {@link IntrospectionQuery} by
194194+ * removing data and information that a client-side consumer, like Graphcache or the
195195+ * `populateExchange`, may not require.
196196+ *
197197+ * At the very least, it will remove system types, descriptions, depreactions,
198198+ * and source locations. Unless disabled via the options passed, it will also
199199+ * by default remove all scalars, enums, inputs, and directives.
200200+ *
201201+ * @throws
202202+ * If `schema` receives an object that isn’t an {@link IntrospectionQuery}, a
203203+ * {@link TypeError} will be thrown.
204204+ */
171205export const minifyIntrospectionQuery = (
172206 schema: IntrospectionQuery,
173207 opts: MinifySchemaOptions = {}
+25-1
packages/next-urql/src/init-urql-client.ts
···2233let urqlClient: Client | null = null;
4455+/** Resets the `Client` that {@link initUrqlClient} returns.
66+ *
77+ * @remarks
88+ * `resetClient` will force {@link initUrqlClient} to create a new
99+ * {@link Client}, rather than reusing the same `Client` it already
1010+ * created on the client-side.
1111+ *
1212+ * This may be used to force the cache and any state in the `Client`
1313+ * to be cleared and reset.
1414+ */
515export function resetClient() {
616 urqlClient = null;
717}
8181919+/** Creates a {@link Client} the given options.
2020+ *
2121+ * @param clientOptions - {@link ClientOptions} to create the `Client` with.
2222+ * @param canEnableSuspense - Enables React Suspense on the server-side for `react-ssr-prepass`.
2323+ * @returns the created {@link Client}
2424+ *
2525+ * @remarks
2626+ * `initUrqlClient` creates a {@link Client} with the given options,
2727+ * like {@link createClient} does, but reuses the same client when
2828+ * run on the client-side.
2929+ *
3030+ * As long as `canEnableSuspense` is set to `true`, it enables React Suspense
3131+ * mode on the server-side for `react-ssr-prepass`.
3232+ */
933export function initUrqlClient(
1034 clientOptions: ClientOptions,
1135 canEnableSuspense: boolean
1212-): Client | null {
3636+): Client {
1337 // Create a new Client for every server-side rendered request.
1438 // This ensures we reset the state for each rendered page.
1539 // If there is an exising client instance on the client-side, use it.
+76-32
packages/next-urql/src/types.ts
···11-import { GraphQLError } from 'graphql';
22-import { ClientOptions, Exchange, Client } from 'urql';
33-import { NextPageContext } from 'next';
44-import { AppContext } from 'next/app';
11+import type { ClientOptions, Client, SSRExchange, SSRData } from '@urql/core';
22+import type { NextPageContext } from 'next';
33+import type { AppContext } from 'next/app';
5455+/** The Next.js {@link NextPageContext}, as modified by `next-urql`. */
66export interface NextUrqlPageContext extends NextPageContext {
77 urqlClient: Client;
88}
991010+/** The Next.js {@link AppContext}, as modified by `next-urql`. */
1011export interface NextUrqlAppContext extends AppContext {
1112 urqlClient: Client;
1213}
13141415export type NextUrqlContext = NextUrqlPageContext | NextUrqlAppContext;
15161717+/** Passed to {@link withUrqlClient} returning the options a {@link Client} is created with.
1818+ *
1919+ * @param ssrExchange - the `ssrExchange` you must use in your `exchanges` array.
2020+ * @param ctx - Passed when `getInitialProps` is used and set to Next.js’ {@link NextPageContext}.
2121+ * @returns a {@link ClientOptions} configuration object to create a {@link Client} with.
2222+ *
2323+ * @remarks
2424+ * You must define a `getClientConfig` function and pass it to {@link withUrqlClient}.
2525+ *
2626+ * This function defines the options passed to {@link initUrqlClient}.
2727+ * It passes you an `ssrExchange` that you must use in your `exchanges` array.
2828+ *
2929+ * @example
3030+ * ```ts
3131+ * import { cacheExchange, fetchExchange } from '@urql/core';
3232+ * import { withUrqlClient } from 'next-urql';
3333+ *
3434+ * const WrappedPage = withUrqlClient(
3535+ * (ssrExchange) => ({
3636+ * url: 'https://YOUR_API',
3737+ * exchanges: [cacheExchange, ssrExchange, fetchExchange],
3838+ * })
3939+ * )(Page);
4040+ * ```
4141+ */
1642export type NextUrqlClientConfig = (
1743 ssrExchange: SSRExchange,
1844 ctx?: NextPageContext
1945) => ClientOptions;
20462121-export interface WithUrqlState {
2222- urqlState?: SSRData;
2323-}
2424-2525-export interface WithUrqlClient {
4747+/** Props that {@link withUrqlClient} components pass on to your component. */
4848+export interface WithUrqlProps {
4949+ /** The {@link Client} that {@link withUrqlClient} created for your component. */
2650 urqlClient?: Client;
2727-}
2828-2929-export interface WithUrqlProps extends WithUrqlClient, WithUrqlState {
3030- resetUrqlClient?: () => void;
5151+ /** Next.js’ `pageProps` prop, as passed to it by Next.js. */
3152 pageProps: any;
5353+ /** The SSR data that {@link withUrqlClient} created for your component. */
5454+ urqlState?: SSRData;
5555+ /** Resets the `Client` that on the client-side.
5656+ *
5757+ * @remarks
5858+ * `resetUrqlClient` will force a new {@link Client} to be created
5959+ * on the client-side, rather than the same `Client` with the same
6060+ * server-side data to be reused.
6161+ *
6262+ * This may be used to force the cache and any state in the `Client`
6363+ * to be cleared and reset.
6464+ */
6565+ resetUrqlClient?(): void;
3266 [key: string]: any;
3367}
34683535-export interface SerializedResult {
3636- data?: any;
3737- error?: {
3838- graphQLErrors: Array<Partial<GraphQLError> | string>;
3939- networkError?: string;
4040- };
4141-}
4242-4343-export interface SSRData {
4444- [key: string]: SerializedResult;
4545-}
4646-4747-export interface SSRExchange extends Exchange {
4848- /** Rehydrates cached data */
4949- restoreData(data: SSRData): void;
5050- /** Extracts cached data */
5151- extractData(): SSRData;
5252-}
5353-6969+/** Options that may be passed to the {@link withUrqlClient} wrapper function. */
5470export interface WithUrqlClientOptions {
7171+ /** Enables automatic server-side rendering mode.
7272+ *
7373+ * @remarks
7474+ * When enabled, {@link withUrqlClient} will add a `getInitialProps`
7575+ * function to the resulting component, even if you haven't defined
7676+ * one.
7777+ *
7878+ * This function will automatically capture `urql`'s SSR state on the
7979+ * server-side and rehydrate it on the client-side, unless
8080+ * {@link WithUrqlClientOptions.neverSuspend} is `true`.
8181+ */
5582 ssr?: boolean;
8383+ /** Disables automatic server-side rendering, even if a `getInitialProps` function is defined.
8484+ *
8585+ * @remarks
8686+ * When enabled, {@link withUrqlClient} will never execute queries
8787+ * on the server-side automatically, and will instead rely on you
8888+ * to do so manually.
8989+ */
5690 neverSuspend?: boolean;
9191+ /** Enables reexecuting operations on the client-side after rehydration.
9292+ *
9393+ * @remarks
9494+ * When enabled, `staleWhileRevalidate` will reexecute GraphQL queries on
9595+ * the client-side, if they’ve been rehydrated from SSR state.
9696+ *
9797+ * This is useful if you, for instance, cache your server-side rendered
9898+ * pages, or if you use `getStaticProps` and wish to get this data
9999+ * updated.
100100+ */
57101 staleWhileRevalidate?: boolean;
58102}
+40-17
packages/next-urql/src/with-urql-client.ts
···66 ReactNode,
77 ReactElement,
88} from 'react';
99-import ssrPrepass from 'react-ssr-prepass';
1010-import { NextComponentType, NextPage, NextPageContext } from 'next';
1111-import NextApp, { AppContext } from 'next/app';
1291310import {
1411 Provider,
1212+ SSRExchange,
1513 ssrExchange,
1616- dedupExchange,
1714 cacheExchange,
1815 fetchExchange,
1916} from 'urql';
20171818+import ssrPrepass from 'react-ssr-prepass';
1919+import { NextComponentType, NextPage, NextPageContext } from 'next';
2020+import NextApp, { AppContext } from 'next/app';
2121+2122import { initUrqlClient, resetClient } from './init-urql-client';
22232324import {
···2526 NextUrqlContext,
2627 WithUrqlProps,
2728 WithUrqlClientOptions,
2828- SSRExchange,
2929} from './types';
30303131let ssr: SSRExchange;
···3333 getLayout?: (page: ReactElement) => ReactNode;
3434};
35353636+/** Creates a wrapper for Next.js Page, App, or Document components that rehydrates `urql` state.
3737+ *
3838+ * @param getClientConfig - function used to create the {@link Client}
3939+ * @param options - optional {@link WithUrqlClientOptions} configuration options
4040+ * @returns a higher-order component function, which you can pass a Next.js page or app component.
4141+ *
4242+ * @remarks
4343+ * Used to wrap a Next.js page or app component. It will create a {@link Client} and passes
4444+ * it on to the child component and adds a React Provider for it.
4545+ *
4646+ * It will restore any page’s `pageProps.urqlState` with the {@link SSRExchange} and also
4747+ * supports doing this automatically when the {@link WithUrqlClientOptions.ssr} option
4848+ * is enabled.
4949+ *
5050+ * If you don’t define the above option, you will have to write `getServerSideProps` or
5151+ * `getStaticProps` methods on your component manually.
5252+ *
5353+ * @see {@link https://urql.dev/goto/docs/advanced/server-side-rendering/#nextjs} for more documentation.
5454+ *
5555+ * @example
5656+ * ```ts
5757+ * import { cacheExchange, fetchExchange } from '@urql/core';
5858+ * import { withUrqlClient } from 'next-urql';
5959+ *
6060+ * const WrappedPage = withUrqlClient(
6161+ * (ssrExchange) => ({
6262+ * url: 'https://YOUR_API',
6363+ * exchanges: [cacheExchange, ssrExchange, fetchExchange],
6464+ * }),
6565+ * { ssr: true },
6666+ * )(Page);
6767+ * ```
6868+ */
3669export function withUrqlClient(
3770 getClientConfig: NextUrqlClientConfig,
3871 options?: WithUrqlClientOptions
···77110 const clientConfig = getClientConfig(ssr);
78111 if (!clientConfig.exchanges) {
79112 // When the user does not provide exchanges we make the default assumption.
8080- clientConfig.exchanges = [
8181- dedupExchange,
8282- cacheExchange,
8383- ssr,
8484- fetchExchange,
8585- ];
113113+ clientConfig.exchanges = [cacheExchange, ssr, fetchExchange];
86114 }
8711588116 return initUrqlClient(clientConfig, shouldEnableSuspense)!;
···129157 const clientConfig = getClientConfig(ssrCache, ctx);
130158 if (!clientConfig.exchanges) {
131159 // When the user does not provide exchanges we make the default assumption.
132132- clientConfig.exchanges = [
133133- dedupExchange,
134134- cacheExchange,
135135- ssrCache,
136136- fetchExchange,
137137- ];
160160+ clientConfig.exchanges = [cacheExchange, ssrCache, fetchExchange];
138161 }
139162140163 const urqlClient = initUrqlClient(clientConfig, !options!.neverSuspend);
+30-12
packages/preact-urql/src/components/Mutation.ts
···11import { VNode } from 'preact';
22import { DocumentNode } from 'graphql';
33-import {
44- AnyVariables,
55- TypedDocumentNode,
66- OperationResult,
77- OperationContext,
88-} from '@urql/core';
99-import { useMutation, UseMutationState } from '../hooks';
33+import { AnyVariables, TypedDocumentNode } from '@urql/core';
44+55+import { useMutation, UseMutationState, UseMutationExecute } from '../hooks';
10677+/** Props accepted by {@link Mutation}.
88+ *
99+ * @remarks
1010+ * `MutationProps` are the props accepted by the {@link Mutation} component.
1111+ *
1212+ * The result, the {@link MutationState} object, will be passed to
1313+ * a {@link MutationProps.children} function, passed as children
1414+ * to the `Mutation` component.
1515+ */
1116export interface MutationProps<
1217 Data = any,
1318 Variables extends AnyVariables = AnyVariables
1419> {
2020+ /* The GraphQL mutation document that {@link useMutation} will execute. */
1521 query: DocumentNode | TypedDocumentNode<Data, Variables> | string;
1616- children: (arg: MutationState<Data, Variables>) => VNode<any>;
2222+ children(arg: MutationState<Data, Variables>): VNode<any>;
1723}
18242525+/** Object that {@link MutationProps.children} is called with.
2626+ *
2727+ * @remarks
2828+ * This is an extented {@link UseMutationstate} with an added
2929+ * {@link MutationState.executeMutation} method, which is usually
3030+ * part of a tuple returned by {@link useMutation}.
3131+ */
1932export interface MutationState<
2033 Data = any,
2134 Variables extends AnyVariables = AnyVariables
2235> extends UseMutationState<Data, Variables> {
2323- executeMutation: (
2424- variables: Variables,
2525- context?: Partial<OperationContext>
2626- ) => Promise<OperationResult<Data, Variables>>;
3636+ /** Alias to {@link useMutation}’s `executeMutation` function. */
3737+ executeMutation: UseMutationExecute<Data, Variables>;
2738}
28394040+/** Component Wrapper around {@link useMutation} to run a GraphQL query.
4141+ *
4242+ * @remarks
4343+ * `Mutation` is a component wrapper around the {@link useMutation} hook
4444+ * that calls the {@link MutationProps.children} prop, as a function,
4545+ * with the {@link MutationState} object.
4646+ */
2947export function Mutation<
3048 Data = any,
3149 Variables extends AnyVariables = AnyVariables
+35-4
packages/preact-urql/src/components/Query.ts
···11import { VNode } from 'preact';
22-import { AnyVariables, OperationContext } from '@urql/core';
33-import { useQuery, UseQueryArgs, UseQueryState } from '../hooks';
22+import { AnyVariables } from '@urql/core';
33+44+import {
55+ useQuery,
66+ UseQueryArgs,
77+ UseQueryState,
88+ UseQueryExecute,
99+} from '../hooks';
4101111+/** Props accepted by {@link Query}.
1212+ *
1313+ * @remarks
1414+ * `QueryProps` are the props accepted by the {@link Query} component,
1515+ * which is identical to {@link UseQueryArgs}.
1616+ *
1717+ * The result, the {@link QueryState} object, will be passed to
1818+ * a {@link QueryProps.children} function, passed as children
1919+ * to the `Query` component.
2020+ */
521export type QueryProps<
622 Data = any,
723 Variables extends AnyVariables = AnyVariables
824> = UseQueryArgs<Variables, Data> & {
99- children: (arg: QueryState<Data, Variables>) => VNode<any>;
2525+ children(arg: QueryState<Data, Variables>): VNode<any>;
1026};
11272828+/** Object that {@link QueryProps.children} is called with.
2929+ *
3030+ * @remarks
3131+ * This is an extented {@link UseQueryState} with an added
3232+ * {@link QueryState.executeQuery} method, which is usually
3333+ * part of a tuple returned by {@link useQuery}.
3434+ */
1235export interface QueryState<
1336 Data = any,
1437 Variables extends AnyVariables = AnyVariables
1538> extends UseQueryState<Data, Variables> {
1616- executeQuery: (opts?: Partial<OperationContext>) => void;
3939+ /** Alias to {@link useQuery}’s `executeQuery` function. */
4040+ executeQuery: UseQueryExecute;
1741}
18424343+/** Component Wrapper around {@link useQuery} to run a GraphQL query.
4444+ *
4545+ * @remarks
4646+ * `Query` is a component wrapper around the {@link useQuery} hook
4747+ * that calls the {@link QueryProps.children} prop, as a function,
4848+ * with the {@link QueryState} object.
4949+ */
1950export function Query<
2051 Data = any,
2152 Variables extends AnyVariables = AnyVariables
···11import { VNode } from 'preact';
22-import { AnyVariables, OperationContext } from '@urql/core';
22+import { AnyVariables } from '@urql/core';
3344import {
55 useSubscription,
66 UseSubscriptionArgs,
77 UseSubscriptionState,
88+ UseSubscriptionExecute,
89 SubscriptionHandler,
910} from '../hooks';
10111212+/** Props accepted by {@link Subscription}.
1313+ *
1414+ * @remarks
1515+ * `SubscriptionProps` are the props accepted by the {@link Subscription} component,
1616+ * which is identical to {@link UseSubscriptionArgs} with an added
1717+ * {@link SubscriptionProps.handler} prop, which {@link useSubscription} usually
1818+ * accepts as an additional argument.
1919+ *
2020+ * The result, the {@link SubscriptionState} object, will be passed to
2121+ * a {@link SubscriptionProps.children} function, passed as children
2222+ * to the `Subscription` component.
2323+ */
1124export type SubscriptionProps<
1225 Data = any,
1326 Result = Data,
1427 Variables extends AnyVariables = AnyVariables
1528> = UseSubscriptionArgs<Variables, Data> & {
2929+ /** Accepts the {@link SubscriptionHandler} as a prop. */
1630 handler?: SubscriptionHandler<Data, Result>;
1717- children: (arg: SubscriptionState<Result, Variables>) => VNode<any>;
3131+ children(arg: SubscriptionState<Result, Variables>): VNode<any>;
1832};
19333434+/** Object that {@link SubscriptionProps.children} is called with.
3535+ *
3636+ * @remarks
3737+ * This is an extented {@link UseSubscriptionState} with an added
3838+ * {@link SubscriptionState.executeSubscription} method, which is usually
3939+ * part of a tuple returned by {@link useSubscription}.
4040+ */
2041export interface SubscriptionState<
2142 Data = any,
2243 Variables extends AnyVariables = AnyVariables
2344> extends UseSubscriptionState<Data, Variables> {
2424- executeSubscription: (opts?: Partial<OperationContext>) => void;
4545+ /** Alias to {@link useSubscription}’s `executeMutation` function. */
4646+ executeSubscription: UseSubscriptionExecute;
2547}
26484949+/** Component Wrapper around {@link useSubscription} to run a GraphQL subscription.
5050+ *
5151+ * @remarks
5252+ * `Subscription` is a component wrapper around the {@link useSubscription} hook
5353+ * that calls the {@link SubscriptionProps.children} prop, as a function,
5454+ * with the {@link SubscriptionState} object.
5555+ */
2756export function Subscription<
2857 Data = any,
2958 Result = Data,
+54
packages/preact-urql/src/context.ts
···33import { Client } from '@urql/core';
4455const OBJ = {};
66+77+/** `@urql/preact`'s Preact Context.
88+ *
99+ * @remarks
1010+ * The Preact Context that `urql`’s {@link Client} will be provided with.
1111+ * You may use the reexported {@link Provider} to provide a `Client` as well.
1212+ */
613export const Context: import('preact').Context<Client | object> =
714 createContext(OBJ);
1515+1616+/** Provider for `urql`’s {@link Client} to GraphQL hooks.
1717+ *
1818+ * @remarks
1919+ * `Provider` accepts a {@link Client} and provides it to all GraphQL hooks,
2020+ * and {@link useClient}.
2121+ *
2222+ * You should make sure to create a {@link Client} and provide it with the
2323+ * `Provider` to parts of your component tree that use GraphQL hooks.
2424+ *
2525+ * @example
2626+ * ```tsx
2727+ * import { Provider } from '@urql/preact';
2828+ * // All of `@urql/core` is also re-exported by `@urql/preact`:
2929+ * import { Client, cacheExchange, fetchExchange } from '@urql/core';
3030+ *
3131+ * const client = new Client({
3232+ * url: 'https://API',
3333+ * exchanges: [cacheExchange, fetchExchange],
3434+ * });
3535+ *
3636+ * const App = () => (
3737+ * <Provider value={client}>
3838+ * <Component />
3939+ * </Provider>
4040+ * );
4141+ * ```
4242+ */
4343+844export const Provider: import('preact').Provider<Client | object> =
945 Context.Provider;
4646+4747+/** Preact Consumer component, providing the {@link Client} provided on a parent component.
4848+ * @remarks
4949+ * This is an alias for {@link Context.Consumer}.
5050+ */
1051export const Consumer: import('preact').Consumer<Client | object> =
1152 Context.Consumer;
12531354Context.displayName = 'UrqlContext';
14555656+/** Hook returning a {@link Client} from {@link Context}.
5757+ *
5858+ * @remarks
5959+ * `useClient` is a convenience hook, which accesses `@urql/preact`'s {@link Context}
6060+ * and returns the {@link Client} defined on it.
6161+ *
6262+ * This will be the {@link Client} you passed to a {@link Provider}
6363+ * you wrapped your elements containing this hook with.
6464+ *
6565+ * @throws
6666+ * In development, if the component you call `useClient()` in is
6767+ * not wrapped in a {@link Provider}, an error is thrown.
6868+ */
1569export const useClient = (): Client => {
1670 const client = useContext(Context);
1771
+110-7
packages/preact-urql/src/hooks/useMutation.ts
···1515import { useClient } from '../context';
1616import { initialState } from './constants';
17171818+/** State of the last mutation executed by your {@link useMutation} hook.
1919+ *
2020+ * @remarks
2121+ * `UseMutationState` is returned (in a tuple) by {@link useMutation} and
2222+ * gives you the {@link OperationResult} of the last mutation executed
2323+ * with {@link UseMutationExecute}.
2424+ *
2525+ * Even if the mutation document passed to {@link useMutation} changes,
2626+ * the state isn’t reset, so you can keep displaying the previous result.
2727+ */
1828export interface UseMutationState<
1929 Data = any,
2030 Variables extends AnyVariables = AnyVariables
2131> {
3232+ /** Indicates whether `useMutation` is currently executing a mutation. */
2233 fetching: boolean;
3434+ /** Indicates that the mutation result is not fresh.
3535+ *
3636+ * @remarks
3737+ * The `stale` flag is set to `true` when a new result for the mutation
3838+ * is expected.
3939+ * This is mostly unused for mutations and will rarely affect you, and
4040+ * is more relevant for queries.
4141+ *
4242+ * @see {@link OperationResult.stale} for the source of this value.
4343+ */
2344 stale: boolean;
4545+ /** The {@link OperationResult.data} for the executed mutation. */
2446 data?: Data;
4747+ /** The {@link OperationResult.error} for the executed mutation. */
2548 error?: CombinedError;
4949+ /** The {@link OperationResult.extensions} for the executed mutation. */
2650 extensions?: Record<string, any>;
5151+ /** The {@link Operation} that the current state is for.
5252+ *
5353+ * @remarks
5454+ * This is the mutation {@link Operation} that has last been executed.
5555+ * When {@link UseQueryState.fetching} is `true`, this is the
5656+ * last `Operation` that the current state was for.
5757+ */
2758 operation?: Operation<Data, Variables>;
2859}
29606161+/** Triggers {@link useMutation} to execute its GraphQL mutation operation.
6262+ *
6363+ * @param variables - variables using which the mutation will be executed.
6464+ * @param context - optionally, context options that will be merged with the hook's
6565+ * {@link UseQueryArgs.context} options and the `Client`’s options.
6666+ * @returns the {@link OperationResult} of the mutation.
6767+ *
6868+ * @remarks
6969+ * When called, {@link useMutation} will start the GraphQL mutation
7070+ * it currently holds and use the `variables` passed to it.
7171+ *
7272+ * Once the mutation response comes back from the API, its
7373+ * returned promise will resolve to the mutation’s {@link OperationResult}
7474+ * and the {@link UseMutationState} will be updated with the result.
7575+ *
7676+ * @example
7777+ * ```ts
7878+ * const [result, executeMutation] = useMutation(UpdateTodo);
7979+ * const start = async ({ id, title }) => {
8080+ * const result = await executeMutation({ id, title });
8181+ * };
8282+ */
8383+export type UseMutationExecute<
8484+ Data = any,
8585+ Variables extends AnyVariables = AnyVariables
8686+> = (
8787+ variables: Variables,
8888+ context?: Partial<OperationContext>
8989+) => Promise<OperationResult<Data, Variables>>;
9090+9191+/** Result tuple returned by the {@link useMutation} hook.
9292+ *
9393+ * @remarks
9494+ * Similarly to a `useState` hook’s return value,
9595+ * the first element is the {@link useMutation}’s state, updated
9696+ * as mutations are executed with the second value, which is
9797+ * used to start mutations and is a {@link UseMutationExecute}
9898+ * function.
9999+ */
30100export type UseMutationResponse<
31101 Data = any,
32102 Variables extends AnyVariables = AnyVariables
3333-> = [
3434- UseMutationState<Data, Variables>,
3535- (
3636- variables: Variables,
3737- context?: Partial<OperationContext>
3838- ) => Promise<OperationResult<Data, Variables>>
3939-];
103103+> = [UseMutationState<Data, Variables>, UseMutationExecute<Data, Variables>];
40104105105+/** Hook to create a GraphQL mutation, run by passing variables to the returned execute function.
106106+ *
107107+ * @param query - a GraphQL mutation document which `useMutation` will execute.
108108+ * @returns a {@link UseMutationResponse} tuple of a {@link UseMutationState} result,
109109+ * and an execute function to start the mutation.
110110+ *
111111+ * @remarks
112112+ * `useMutation` allows GraphQL mutations to be defined and keeps its state
113113+ * after the mutation is started with the returned execute function.
114114+ *
115115+ * Given a GraphQL mutation document it returns state to keep track of the
116116+ * mutation state and a {@link UseMutationExecute} function, which accepts
117117+ * variables for the mutation to be executed.
118118+ * Once called, the mutation executes and the state will be updated with
119119+ * the mutation’s result.
120120+ *
121121+ * @see {@link https://urql.dev/goto/docs/basics/react-preact/#mutations} for `useMutation` docs.
122122+ *
123123+ * @example
124124+ * ```ts
125125+ * import { gql, useMutation } from '@urql/preact';
126126+ *
127127+ * const UpdateTodo = gql`
128128+ * mutation ($id: ID!, $title: String!) {
129129+ * updateTodo(id: $id, title: $title) {
130130+ * id, title
131131+ * }
132132+ * }
133133+ * `;
134134+ *
135135+ * const UpdateTodo = () => {
136136+ * const [result, executeMutation] = useMutation(UpdateTodo);
137137+ * const start = async ({ id, title }) => {
138138+ * const result = await executeMutation({ id, title });
139139+ * };
140140+ * // ...
141141+ * };
142142+ * ```
143143+ */
41144export function useMutation<
42145 Data = any,
43146 Variables extends AnyVariables = AnyVariables
+159-5
packages/preact-urql/src/hooks/useQuery.ts
···2828import { useRequest } from './useRequest';
2929import { initialState } from './constants';
30303131+/** Input arguments for the {@link useQuery} hook.
3232+ *
3333+ * @param query - The GraphQL query that `useQuery` executes.
3434+ * @param variables - The variables for the GraphQL query that `useQuery` executes.
3535+ */
3136export type UseQueryArgs<
3237 Variables extends AnyVariables = AnyVariables,
3338 Data = any
3439> = {
4040+ /** Updates the {@link RequestPolicy} for the executed GraphQL query operation.
4141+ *
4242+ * @remarks
4343+ * `requestPolicy` modifies the {@link RequestPolicy} of the GraphQL query operation
4444+ * that `useQuery` executes, and indicates a caching strategy for cache exchanges.
4545+ *
4646+ * For example, when set to `'cache-and-network'`, {@link useQuery} will
4747+ * receive a cached result with `stale: true` and an API request will be
4848+ * sent in the background.
4949+ *
5050+ * @see {@link OperationContext.requestPolicy} for where this value is set.
5151+ */
3552 requestPolicy?: RequestPolicy;
5353+ /** Updates the {@link OperationContext} for the executed GraphQL query operation.
5454+ *
5555+ * @remarks
5656+ * `context` may be passed to {@link useQuery}, to update the {@link OperationContext}
5757+ * of a query operation. This may be used to update the `context` that exchanges
5858+ * will receive for a single hook.
5959+ *
6060+ * Hint: This should be wrapped in a `useMemo` hook, to make sure that your
6161+ * component doesn’t infinitely update.
6262+ *
6363+ * @example
6464+ * ```ts
6565+ * const [result, reexecute] = useQuery({
6666+ * query,
6767+ * context: useMemo(() => ({
6868+ * additionalTypenames: ['Item'],
6969+ * }), [])
7070+ * });
7171+ * ```
7272+ */
3673 context?: Partial<OperationContext>;
7474+ /** Prevents {@link useQuery} from automatically executing GraphQL query operations.
7575+ *
7676+ * @remarks
7777+ * `pause` may be set to `true` to stop {@link useQuery} from executing
7878+ * automatically. The hook will stop receiving updates from the {@link Client}
7979+ * and won’t execute the query operation, until either it’s set to `false`
8080+ * or the {@link UseQueryExecute} function is called.
8181+ *
8282+ * @see {@link https://urql.dev/goto/docs/basics/react-preact/#pausing-usequery} for
8383+ * documentation on the `pause` option.
8484+ */
3785 pause?: boolean;
3886} & GraphQLRequestParams<Data, Variables>;
39878888+/** State of the current query, your {@link useQuery} hook is executing.
8989+ *
9090+ * @remarks
9191+ * `UseQueryState` is returned (in a tuple) by {@link useQuery} and
9292+ * gives you the updating {@link OperationResult} of GraphQL queries.
9393+ *
9494+ * Even when the query and variables passed to {@link useQuery} change,
9595+ * this state preserves the prior state and sets the `fetching` flag to
9696+ * `true`.
9797+ * This allows you to display the previous state, while implementing
9898+ * a separate loading indicator separately.
9999+ */
40100export interface UseQueryState<
41101 Data = any,
42102 Variables extends AnyVariables = AnyVariables
43103> {
104104+ /** Indicates whether `useQuery` is waiting for a new result.
105105+ *
106106+ * @remarks
107107+ * When `useQuery` is passed a new query and/or variables, it will
108108+ * start executing the new query operation and `fetching` is set to
109109+ * `true` until a result arrives.
110110+ *
111111+ * Hint: This is subtly different than whether the query is actually
112112+ * fetching, and doesn’t indicate whether a query is being re-executed
113113+ * in the background. For this, see {@link UseQueryState.stale}.
114114+ */
44115 fetching: boolean;
116116+ /** Indicates that the state is not fresh and a new result will follow.
117117+ *
118118+ * @remarks
119119+ * The `stale` flag is set to `true` when a new result for the query
120120+ * is expected and `useQuery` is waiting for it. This may indicate that
121121+ * a new request is being requested in the background.
122122+ *
123123+ * @see {@link OperationResult.stale} for the source of this value.
124124+ */
45125 stale: boolean;
126126+ /** The {@link OperationResult.data} for the executed query. */
46127 data?: Data;
128128+ /** The {@link OperationResult.error} for the executed query. */
47129 error?: CombinedError;
130130+ /** The {@link OperationResult.extensions} for the executed query. */
48131 extensions?: Record<string, any>;
132132+ /** The {@link Operation} that the current state is for.
133133+ *
134134+ * @remarks
135135+ * This is the {@link Operation} that is currently being executed.
136136+ * When {@link UseQueryState.fetching} is `true`, this is the
137137+ * last `Operation` that the current state was for.
138138+ */
49139 operation?: Operation<Data, Variables>;
50140}
51141142142+/** Triggers {@link useQuery} to execute a new GraphQL query operation.
143143+ *
144144+ * @remarks
145145+ * When called, {@link useQuery} will re-execute the GraphQL query operation
146146+ * it currently holds, even if {@link UseQueryArgs.pause} is set to `true`.
147147+ *
148148+ * This is useful for executing a paused query or re-executing a query
149149+ * and get a new network result, by passing a new request policy.
150150+ *
151151+ * ```ts
152152+ * const [result, reexecuteQuery] = useQuery({ query });
153153+ *
154154+ * const refresh = () => {
155155+ * // Re-execute the query with a network-only policy, skipping the cache
156156+ * reexecuteQuery({ requestPolicy: 'network-only' });
157157+ * };
158158+ * ```
159159+ */
160160+export type UseQueryExecute = (opts?: Partial<OperationContext>) => void;
161161+162162+/** Result tuple returned by the {@link useQuery} hook.
163163+ *
164164+ * @remarks
165165+ * Similarly to a `useState` hook’s return value,
166166+ * the first element is the {@link useQuery}’s result and state,
167167+ * a {@link UseQueryState} object,
168168+ * and the second is used to imperatively re-execute the query
169169+ * via a {@link UseQueryExecute} function.
170170+ */
52171export type UseQueryResponse<
53172 Data = any,
54173 Variables extends AnyVariables = AnyVariables
5555-> = [
5656- UseQueryState<Data, Variables>,
5757- (opts?: Partial<OperationContext>) => void
5858-];
174174+> = [UseQueryState<Data, Variables>, UseQueryExecute];
591756060-/** Convert the Source to a React Suspense source on demand */
176176+/** Convert the Source to a React Suspense source on demand
177177+ * @internal
178178+ */
61179function toSuspenseSource<T>(source: Source<T>): Source<T> {
62180 const shared = share(source);
63181 let cache: T | void;
···9821699217const sources = new Map<number, Source<OperationResult>>();
100218219219+/** Hook to run a GraphQL query and get updated GraphQL results.
220220+ *
221221+ * @param args - a {@link UseQueryArgs} object, to pass a `query`, `variables`, and options.
222222+ * @returns a {@link UseQueryResponse} tuple of a {@link UseQueryState} result, and re-execute function.
223223+ *
224224+ * @remarks
225225+ * `useQuery` allows GraphQL queries to be defined and executed.
226226+ * Given {@link UseQueryArgs.query}, it executes the GraphQL query with the
227227+ * context’s {@link Client}.
228228+ *
229229+ * The returned result updates when the `Client` has new results
230230+ * for the query, and changes when your input `args` change.
231231+ *
232232+ * Additionally, if the `suspense` option is enabled on the `Client`,
233233+ * the `useQuery` hook will suspend instead of indicating that it’s
234234+ * waiting for a result via {@link UseQueryState.fetching}.
235235+ *
236236+ * @see {@link https://urql.dev/goto/docs/basics/react-preact/#queries} for `useQuery` docs.
237237+ *
238238+ * @example
239239+ * ```ts
240240+ * import { gql, useQuery } from '@urql/preact';
241241+ *
242242+ * const TodosQuery = gql`
243243+ * query { todos { id, title } }
244244+ * `;
245245+ *
246246+ * const Todos = () => {
247247+ * const [result, reexecuteQuery] = useQuery({
248248+ * query: TodosQuery,
249249+ * variables: {},
250250+ * });
251251+ * // ...
252252+ * };
253253+ * ```
254254+ */
101255export function useQuery<
102256 Data = any,
103257 Variables extends AnyVariables = AnyVariables
+3-1
packages/preact-urql/src/hooks/useRequest.ts
···77 createRequest,
88} from '@urql/core';
991010-/** Creates a request from a query and variables but preserves reference equality if the key isn't changing */
1010+/** Creates a request from a query and variables but preserves reference equality if the key isn't changing
1111+ * @internal
1212+ */
1113export function useRequest<
1214 Data = any,
1315 Variables extends AnyVariables = AnyVariables
+175-4
packages/preact-urql/src/hooks/useSubscription.ts
···1414import { useRequest } from './useRequest';
1515import { initialState } from './constants';
16161717+/** Input arguments for the {@link useSubscription} hook.
1818+ *
1919+ * @param query - The GraphQL subscription document that `useSubscription` executes.
2020+ * @param variables - The variables for the GraphQL subscription that `useSubscription` executes.
2121+ */
1722export type UseSubscriptionArgs<
1823 Variables extends AnyVariables = AnyVariables,
1924 Data = any
2025> = {
2626+ /** Prevents {@link useSubscription} from automatically starting GraphQL subscriptions.
2727+ *
2828+ * @remarks
2929+ * `pause` may be set to `true` to stop {@link useSubscription} from starting its subscription
3030+ * automatically. The hook will stop receiving updates from the {@link Client}
3131+ * and won’t start the subscription operation, until either it’s set to `false`
3232+ * or the {@link UseSubscriptionExecute} function is called.
3333+ */
2134 pause?: boolean;
3535+ /** Updates the {@link OperationContext} for the executed GraphQL subscription operation.
3636+ *
3737+ * @remarks
3838+ * `context` may be passed to {@link useSubscription}, to update the {@link OperationContext}
3939+ * of a subscription operation. This may be used to update the `context` that exchanges
4040+ * will receive for a single hook.
4141+ *
4242+ * Hint: This should be wrapped in a `useMemo` hook, to make sure that your
4343+ * component doesn’t infinitely update.
4444+ *
4545+ * @example
4646+ * ```ts
4747+ * const [result, reexecute] = useSubscription({
4848+ * query,
4949+ * context: useMemo(() => ({
5050+ * additionalTypenames: ['Item'],
5151+ * }), [])
5252+ * });
5353+ * ```
5454+ */
2255 context?: Partial<OperationContext>;
2356} & GraphQLRequestParams<Data, Variables>;
24575858+/** Combines previous data with an incoming subscription result’s data.
5959+ *
6060+ * @remarks
6161+ * A `SubscriptionHandler` may be passed to {@link useSubscription} to
6262+ * aggregate subscription results into a combined {@link UseSubscriptionState.data}
6363+ * value.
6464+ *
6565+ * This is useful when a subscription event delivers a single item, while
6666+ * you’d like to display a list of events.
6767+ *
6868+ * @example
6969+ * ```ts
7070+ * const NotificationsSubscription = gql`
7171+ * subscription { newNotification { id, text } }
7272+ * `;
7373+ *
7474+ * const combineNotifications = (notifications = [], data) => {
7575+ * return [...notifications, data.newNotification];
7676+ * };
7777+ *
7878+ * const [result, executeSubscription] = useSubscription(
7979+ * { query: NotificationsSubscription },
8080+ * combineNotifications,
8181+ * );
8282+ * ```
8383+ */
2584export type SubscriptionHandler<T, R> = (prev: R | undefined, data: T) => R;
26858686+/** State of the current subscription, your {@link useSubscription} hook is executing.
8787+ *
8888+ * @remarks
8989+ * `UseSubscriptionState` is returned (in a tuple) by {@link useSubscription} and
9090+ * gives you the updating {@link OperationResult} of GraphQL subscriptions.
9191+ *
9292+ * If a {@link SubscriptionHandler} has been passed to `useSubscription` then
9393+ * {@link UseSubscriptionState.data} is instead the updated data as returned
9494+ * by the handler, otherwise it’s the latest result’s data.
9595+ *
9696+ * Hint: Even when the query and variables passed to {@link useSubscription} change,
9797+ * this state preserves the prior state.
9898+ */
2799export interface UseSubscriptionState<
28100 Data = any,
29101 Variables extends AnyVariables = AnyVariables
30102> {
103103+ /** Indicates whether `useSubscription`’s subscription is active.
104104+ *
105105+ * @remarks
106106+ * When `useSubscription` starts a subscription, the `fetching` flag
107107+ * is set to `true` and will remain `true` until the subscription
108108+ * completes on the API, or the {@link UseSubscriptionArgs.pause}
109109+ * flag is set to `true`.
110110+ */
31111 fetching: boolean;
112112+ /** Indicates that the subscription result is not fresh.
113113+ *
114114+ * @remarks
115115+ * This is mostly unused for subscriptions and will rarely affect you, and
116116+ * is more relevant for queries.
117117+ *
118118+ * @see {@link OperationResult.stale} for the source of this value.
119119+ */
32120 stale: boolean;
121121+ /** The {@link OperationResult.data} for the executed subscription, or data returned by a handler.
122122+ *
123123+ * @remarks
124124+ * `data` will be set to the last {@link OperationResult.data} value
125125+ * received for the subscription.
126126+ *
127127+ * It will instead be set to the values that {@link SubscriptionHandler}
128128+ * returned, if a handler has been passed to {@link useSubscription}.
129129+ */
33130 data?: Data;
131131+ /** The {@link OperationResult.error} for the executed subscription. */
34132 error?: CombinedError;
133133+ /** The {@link OperationResult.extensions} for the executed mutation. */
35134 extensions?: Record<string, any>;
135135+ /** The {@link Operation} that the current state is for.
136136+ *
137137+ * @remarks
138138+ * This is the subscription {@link Operation} that is currently active.
139139+ * When {@link UseSubscriptionState.fetching} is `true`, this is the
140140+ * last `Operation` that the current state was for.
141141+ */
36142 operation?: Operation<Data, Variables>;
37143}
38144145145+/** Triggers {@link useSubscription} to reexecute a GraphQL subscription operation.
146146+ *
147147+ * @param opts - optionally, context options that will be merged with the hook's
148148+ * {@link UseSubscriptionArgs.context} options and the `Client`’s options.
149149+ *
150150+ * @remarks
151151+ * When called, {@link useSubscription} will restart the GraphQL subscription
152152+ * operation it currently holds. If {@link UseSubscriptionArgs.pause} is set
153153+ * to `true`, it will start executing the subscription.
154154+ *
155155+ * ```ts
156156+ * const [result, executeSubscription] = useSubscription({
157157+ * query,
158158+ * pause: true,
159159+ * });
160160+ *
161161+ * const start = () => {
162162+ * executeSubscription();
163163+ * };
164164+ * ```
165165+ */
166166+export type UseSubscriptionExecute = (opts?: Partial<OperationContext>) => void;
167167+168168+/** Result tuple returned by the {@link useSubscription} hook.
169169+ *
170170+ * @remarks
171171+ * Similarly to a `useState` hook’s return value,
172172+ * the first element is the {@link useSubscription}’s state,
173173+ * a {@link UseSubscriptionState} object,
174174+ * and the second is used to imperatively re-execute or start the subscription
175175+ * via a {@link UseMutationExecute} function.
176176+ */
39177export type UseSubscriptionResponse<
40178 Data = any,
41179 Variables extends AnyVariables = AnyVariables
4242-> = [
4343- UseSubscriptionState<Data, Variables>,
4444- (opts?: Partial<OperationContext>) => void
4545-];
180180+> = [UseSubscriptionState<Data, Variables>, UseSubscriptionExecute];
46181182182+/** Hook to run a GraphQL subscription and get updated GraphQL results.
183183+ *
184184+ * @param args - a {@link UseSubscriptionArgs} object, to pass a `query`, `variables`, and options.
185185+ * @param handler - optionally, a {@link SubscriptionHandler} function to combine multiple subscription results.
186186+ * @returns a {@link UseSubscriptionResponse} tuple of a {@link UseSubscriptionState} result, and an execute function.
187187+ *
188188+ * @remarks
189189+ * `useSubscription` allows GraphQL subscriptions to be defined and executed.
190190+ * Given {@link UseSubscriptionArgs.query}, it executes the GraphQL subscription with the
191191+ * context’s {@link Client}.
192192+ *
193193+ * The returned result updates when the `Client` has new results
194194+ * for the subscription, and `data` is updated with the result’s data
195195+ * or with the `data` that a `handler` returns.
196196+ *
197197+ * @example
198198+ * ```ts
199199+ * import { gql, useSubscription } from '@urql/preact';
200200+ *
201201+ * const NotificationsSubscription = gql`
202202+ * subscription { newNotification { id, text } }
203203+ * `;
204204+ *
205205+ * const combineNotifications = (notifications = [], data) => {
206206+ * return [...notifications, data.newNotification];
207207+ * };
208208+ *
209209+ * const Notifications = () => {
210210+ * const [result, executeSubscription] = useSubscription(
211211+ * { query: NotificationsSubscription },
212212+ * combineNotifications,
213213+ * );
214214+ * // ...
215215+ * };
216216+ * ```
217217+ */
47218export function useSubscription<
48219 Data = any,
49220 Result = Data,
+30-12
packages/react-urql/src/components/Mutation.ts
···11import { DocumentNode } from 'graphql';
22import { ReactElement } from 'react';
33-import {
44- AnyVariables,
55- TypedDocumentNode,
66- OperationResult,
77- OperationContext,
88-} from '@urql/core';
99-import { useMutation, UseMutationState } from '../hooks';
33+import { AnyVariables, TypedDocumentNode } from '@urql/core';
44+55+import { useMutation, UseMutationState, UseMutationExecute } from '../hooks';
10677+/** Props accepted by {@link Mutation}.
88+ *
99+ * @remarks
1010+ * `MutationProps` are the props accepted by the {@link Mutation} component.
1111+ *
1212+ * The result, the {@link MutationState} object, will be passed to
1313+ * a {@link MutationProps.children} function, passed as children
1414+ * to the `Mutation` component.
1515+ */
1116export interface MutationProps<
1217 Data = any,
1318 Variables extends AnyVariables = AnyVariables
1419> {
2020+ /* The GraphQL mutation document that {@link useMutation} will execute. */
1521 query: DocumentNode | TypedDocumentNode<Data, Variables> | string;
1616- children: (arg: MutationState<Data, Variables>) => ReactElement<any>;
2222+ children(arg: MutationState<Data, Variables>): ReactElement<any>;
1723}
18242525+/** Object that {@link MutationProps.children} is called with.
2626+ *
2727+ * @remarks
2828+ * This is an extented {@link UseMutationstate} with an added
2929+ * {@link MutationState.executeMutation} method, which is usually
3030+ * part of a tuple returned by {@link useMutation}.
3131+ */
1932export interface MutationState<
2033 Data = any,
2134 Variables extends AnyVariables = AnyVariables
2235> extends UseMutationState<Data, Variables> {
2323- executeMutation: (
2424- variables: Variables,
2525- context?: Partial<OperationContext>
2626- ) => Promise<OperationResult<Data, Variables>>;
3636+ /** Alias to {@link useMutation}’s `executeMutation` function. */
3737+ executeMutation: UseMutationExecute<Data, Variables>;
2738}
28394040+/** Component Wrapper around {@link useMutation} to run a GraphQL query.
4141+ *
4242+ * @remarks
4343+ * `Mutation` is a component wrapper around the {@link useMutation} hook
4444+ * that calls the {@link MutationProps.children} prop, as a function,
4545+ * with the {@link MutationState} object.
4646+ */
2947export function Mutation<
3048 Data = any,
3149 Variables extends AnyVariables = AnyVariables
+35-4
packages/react-urql/src/components/Query.ts
···11import { ReactElement } from 'react';
22-import { AnyVariables, OperationContext } from '@urql/core';
33-import { useQuery, UseQueryArgs, UseQueryState } from '../hooks';
22+import { AnyVariables } from '@urql/core';
33+44+import {
55+ useQuery,
66+ UseQueryArgs,
77+ UseQueryState,
88+ UseQueryExecute,
99+} from '../hooks';
4101111+/** Props accepted by {@link Query}.
1212+ *
1313+ * @remarks
1414+ * `QueryProps` are the props accepted by the {@link Query} component,
1515+ * which is identical to {@link UseQueryArgs}.
1616+ *
1717+ * The result, the {@link QueryState} object, will be passed to
1818+ * a {@link QueryProps.children} function, passed as children
1919+ * to the `Query` component.
2020+ */
521export type QueryProps<
622 Data = any,
723 Variables extends AnyVariables = AnyVariables
824> = UseQueryArgs<Variables, Data> & {
99- children: (arg: QueryState<Data, Variables>) => ReactElement<any>;
2525+ children(arg: QueryState<Data, Variables>): ReactElement<any>;
1026};
11272828+/** Object that {@link QueryProps.children} is called with.
2929+ *
3030+ * @remarks
3131+ * This is an extented {@link UseQueryState} with an added
3232+ * {@link QueryState.executeQuery} method, which is usually
3333+ * part of a tuple returned by {@link useQuery}.
3434+ */
1235export interface QueryState<
1336 Data = any,
1437 Variables extends AnyVariables = AnyVariables
1538> extends UseQueryState<Data, Variables> {
1616- executeQuery: (opts?: Partial<OperationContext>) => void;
3939+ /** Alias to {@link useQuery}’s `executeQuery` function. */
4040+ executeQuery: UseQueryExecute;
1741}
18424343+/** Component Wrapper around {@link useQuery} to run a GraphQL query.
4444+ *
4545+ * @remarks
4646+ * `Query` is a component wrapper around the {@link useQuery} hook
4747+ * that calls the {@link QueryProps.children} prop, as a function,
4848+ * with the {@link QueryState} object.
4949+ */
1950export function Query<
2051 Data = any,
2152 Variables extends AnyVariables = AnyVariables
···11import { ReactElement } from 'react';
22-import { AnyVariables, OperationContext } from '@urql/core';
22+import { AnyVariables } from '@urql/core';
3344import {
55 useSubscription,
66 UseSubscriptionArgs,
77 UseSubscriptionState,
88+ UseSubscriptionExecute,
89 SubscriptionHandler,
910} from '../hooks';
10111212+/** Props accepted by {@link Subscription}.
1313+ *
1414+ * @remarks
1515+ * `SubscriptionProps` are the props accepted by the {@link Subscription} component,
1616+ * which is identical to {@link UseSubscriptionArgs} with an added
1717+ * {@link SubscriptionProps.handler} prop, which {@link useSubscription} usually
1818+ * accepts as an additional argument.
1919+ *
2020+ * The result, the {@link SubscriptionState} object, will be passed to
2121+ * a {@link SubscriptionProps.children} function, passed as children
2222+ * to the `Subscription` component.
2323+ */
1124export type SubscriptionProps<
1225 Data = any,
1326 Result = Data,
1427 Variables extends AnyVariables = AnyVariables
1528> = UseSubscriptionArgs<Variables, Data> & {
1629 handler?: SubscriptionHandler<Data, Result>;
1717- children: (arg: SubscriptionState<Result, Variables>) => ReactElement<any>;
3030+ children(arg: SubscriptionState<Result, Variables>): ReactElement<any>;
1831};
19323333+/** Object that {@link SubscriptionProps.children} is called with.
3434+ *
3535+ * @remarks
3636+ * This is an extented {@link UseSubscriptionState} with an added
3737+ * {@link SubscriptionState.executeSubscription} method, which is usually
3838+ * part of a tuple returned by {@link useSubscription}.
3939+ */
2040export interface SubscriptionState<
2141 Data = any,
2242 Variables extends AnyVariables = AnyVariables
2343> extends UseSubscriptionState<Data, Variables> {
2424- executeSubscription: (opts?: Partial<OperationContext>) => void;
4444+ /** Alias to {@link useSubscription}’s `executeMutation` function. */
4545+ executeSubscription: UseSubscriptionExecute;
2546}
26474848+/** Component Wrapper around {@link useSubscription} to run a GraphQL subscription.
4949+ *
5050+ * @remarks
5151+ * `Subscription` is a component wrapper around the {@link useSubscription} hook
5252+ * that calls the {@link SubscriptionProps.children} prop, as a function,
5353+ * with the {@link SubscriptionState} object.
5454+ */
2755export function Subscription<
2856 Data = any,
2957 Result = Data,
+53
packages/react-urql/src/context.ts
···22import { Client } from '@urql/core';
3344const OBJ = {};
55+66+/** `urql`'s React Context.
77+ *
88+ * @remarks
99+ * The React Context that `urql`’s {@link Client} will be provided with.
1010+ * You may use the reexported {@link Provider} to provide a `Client` as well.
1111+ */
512export const Context: import('react').Context<Client | object> =
613 createContext(OBJ);
1414+1515+/** Provider for `urql`'s {@link Client} to GraphQL hooks.
1616+ *
1717+ * @remarks
1818+ * `Provider` accepts a {@link Client} and provides it to all GraphQL hooks,
1919+ * and {@link useClient}.
2020+ *
2121+ * You should make sure to create a {@link Client} and provide it with the
2222+ * `Provider` to parts of your component tree that use GraphQL hooks.
2323+ *
2424+ * @example
2525+ * ```tsx
2626+ * import { Provider } from 'urql';
2727+ * // All of `@urql/core` is also re-exported by `urql`:
2828+ * import { Client, cacheExchange, fetchExchange } from '@urql/core';
2929+ *
3030+ * const client = new Client({
3131+ * url: 'https://API',
3232+ * exchanges: [cacheExchange, fetchExchange],
3333+ * });
3434+ *
3535+ * const App = () => (
3636+ * <Provider value={client}>
3737+ * <Component />
3838+ * </Provider>
3939+ * );
4040+ * ```
4141+ */
742export const Provider: import('react').Provider<Client | object> =
843 Context.Provider;
4444+4545+/** React Consumer component, providing the {@link Client} provided on a parent component.
4646+ * @remarks
4747+ * This is an alias for {@link Context.Consumer}.
4848+ */
949export const Consumer: import('react').Consumer<Client | object> =
1050 Context.Consumer;
11511252Context.displayName = 'UrqlContext';
13535454+/** Hook returning a {@link Client} from {@link Context}.
5555+ *
5656+ * @remarks
5757+ * `useClient` is a convenience hook, which accesses `urql`'s {@link Context}
5858+ * and returns the {@link Client} defined on it.
5959+ *
6060+ * This will be the {@link Client} you passed to a {@link Provider}
6161+ * you wrapped your elements containing this hook with.
6262+ *
6363+ * @throws
6464+ * In development, if the component you call `useClient()` in is
6565+ * not wrapped in a {@link Provider}, an error is thrown.
6666+ */
1467export const useClient = (): Client => {
1568 const client = useContext(Context);
1669
+110-7
packages/react-urql/src/hooks/useMutation.ts
···1515import { useClient } from '../context';
1616import { initialState } from './state';
17171818+/** State of the last mutation executed by your {@link useMutation} hook.
1919+ *
2020+ * @remarks
2121+ * `UseMutationState` is returned (in a tuple) by {@link useMutation} and
2222+ * gives you the {@link OperationResult} of the last mutation executed
2323+ * with {@link UseMutationExecute}.
2424+ *
2525+ * Even if the mutation document passed to {@link useMutation} changes,
2626+ * the state isn’t reset, so you can keep displaying the previous result.
2727+ */
1828export interface UseMutationState<
1929 Data = any,
2030 Variables extends AnyVariables = AnyVariables
2131> {
3232+ /** Indicates whether `useMutation` is currently executing a mutation. */
2233 fetching: boolean;
3434+ /** Indicates that the mutation result is not fresh.
3535+ *
3636+ * @remarks
3737+ * The `stale` flag is set to `true` when a new result for the mutation
3838+ * is expected.
3939+ * This is mostly unused for mutations and will rarely affect you, and
4040+ * is more relevant for queries.
4141+ *
4242+ * @see {@link OperationResult.stale} for the source of this value.
4343+ */
2344 stale: boolean;
4545+ /** The {@link OperationResult.data} for the executed mutation. */
2446 data?: Data;
4747+ /** The {@link OperationResult.error} for the executed mutation. */
2548 error?: CombinedError;
4949+ /** The {@link OperationResult.extensions} for the executed mutation. */
2650 extensions?: Record<string, any>;
5151+ /** The {@link Operation} that the current state is for.
5252+ *
5353+ * @remarks
5454+ * This is the mutation {@link Operation} that has last been executed.
5555+ * When {@link UseQueryState.fetching} is `true`, this is the
5656+ * last `Operation` that the current state was for.
5757+ */
2758 operation?: Operation<Data, Variables>;
2859}
29606161+/** Triggers {@link useMutation} to execute its GraphQL mutation operation.
6262+ *
6363+ * @param variables - variables using which the mutation will be executed.
6464+ * @param context - optionally, context options that will be merged with the hook's
6565+ * {@link UseQueryArgs.context} options and the `Client`’s options.
6666+ * @returns the {@link OperationResult} of the mutation.
6767+ *
6868+ * @remarks
6969+ * When called, {@link useMutation} will start the GraphQL mutation
7070+ * it currently holds and use the `variables` passed to it.
7171+ *
7272+ * Once the mutation response comes back from the API, its
7373+ * returned promise will resolve to the mutation’s {@link OperationResult}
7474+ * and the {@link UseMutationState} will be updated with the result.
7575+ *
7676+ * @example
7777+ * ```ts
7878+ * const [result, executeMutation] = useMutation(UpdateTodo);
7979+ * const start = async ({ id, title }) => {
8080+ * const result = await executeMutation({ id, title });
8181+ * };
8282+ */
8383+export type UseMutationExecute<
8484+ Data = any,
8585+ Variables extends AnyVariables = AnyVariables
8686+> = (
8787+ variables: Variables,
8888+ context?: Partial<OperationContext>
8989+) => Promise<OperationResult<Data, Variables>>;
9090+9191+/** Result tuple returned by the {@link useMutation} hook.
9292+ *
9393+ * @remarks
9494+ * Similarly to a `useState` hook’s return value,
9595+ * the first element is the {@link useMutation}’s state, updated
9696+ * as mutations are executed with the second value, which is
9797+ * used to start mutations and is a {@link UseMutationExecute}
9898+ * function.
9999+ */
30100export type UseMutationResponse<
31101 Data = any,
32102 Variables extends AnyVariables = AnyVariables
3333-> = [
3434- UseMutationState<Data, Variables>,
3535- (
3636- variables: Variables,
3737- context?: Partial<OperationContext>
3838- ) => Promise<OperationResult<Data, Variables>>
3939-];
103103+> = [UseMutationState<Data, Variables>, UseMutationExecute<Data, Variables>];
40104105105+/** Hook to create a GraphQL mutation, run by passing variables to the returned execute function.
106106+ *
107107+ * @param query - a GraphQL mutation document which `useMutation` will execute.
108108+ * @returns a {@link UseMutationResponse} tuple of a {@link UseMutationState} result,
109109+ * and an execute function to start the mutation.
110110+ *
111111+ * @remarks
112112+ * `useMutation` allows GraphQL mutations to be defined and keeps its state
113113+ * after the mutation is started with the returned execute function.
114114+ *
115115+ * Given a GraphQL mutation document it returns state to keep track of the
116116+ * mutation state and a {@link UseMutationExecute} function, which accepts
117117+ * variables for the mutation to be executed.
118118+ * Once called, the mutation executes and the state will be updated with
119119+ * the mutation’s result.
120120+ *
121121+ * @see {@link https://urql.dev/goto/urql/docs/basics/react-preact/#mutations} for `useMutation` docs.
122122+ *
123123+ * @example
124124+ * ```ts
125125+ * import { gql, useMutation } from 'urql';
126126+ *
127127+ * const UpdateTodo = gql`
128128+ * mutation ($id: ID!, $title: String!) {
129129+ * updateTodo(id: $id, title: $title) {
130130+ * id, title
131131+ * }
132132+ * }
133133+ * `;
134134+ *
135135+ * const UpdateTodo = () => {
136136+ * const [result, executeMutation] = useMutation(UpdateTodo);
137137+ * const start = async ({ id, title }) => {
138138+ * const result = await executeMutation({ id, title });
139139+ * };
140140+ * // ...
141141+ * };
142142+ * ```
143143+ */
41144export function useMutation<
42145 Data = any,
43146 Variables extends AnyVariables = AnyVariables
+159-4
packages/react-urql/src/hooks/useQuery.ts
···1919import { getCacheForClient } from './cache';
2020import { initialState, computeNextState, hasDepsChanged } from './state';
21212222+/** Input arguments for the {@link useQuery} hook.
2323+ *
2424+ * @param query - The GraphQL query that `useQuery` executes.
2525+ * @param variables - The variables for the GraphQL query that `useQuery` executes.
2626+ */
2227export type UseQueryArgs<
2328 Variables extends AnyVariables = AnyVariables,
2429 Data = any
2530> = {
3131+ /** Updates the {@link RequestPolicy} for the executed GraphQL query operation.
3232+ *
3333+ * @remarks
3434+ * `requestPolicy` modifies the {@link RequestPolicy} of the GraphQL query operation
3535+ * that `useQuery` executes, and indicates a caching strategy for cache exchanges.
3636+ *
3737+ * For example, when set to `'cache-and-network'`, {@link useQuery} will
3838+ * receive a cached result with `stale: true` and an API request will be
3939+ * sent in the background.
4040+ *
4141+ * @see {@link OperationContext.requestPolicy} for where this value is set.
4242+ */
2643 requestPolicy?: RequestPolicy;
4444+ /** Updates the {@link OperationContext} for the executed GraphQL query operation.
4545+ *
4646+ * @remarks
4747+ * `context` may be passed to {@link useQuery}, to update the {@link OperationContext}
4848+ * of a query operation. This may be used to update the `context` that exchanges
4949+ * will receive for a single hook.
5050+ *
5151+ * Hint: This should be wrapped in a `useMemo` hook, to make sure that your
5252+ * component doesn’t infinitely update.
5353+ *
5454+ * @example
5555+ * ```ts
5656+ * const [result, reexecute] = useQuery({
5757+ * query,
5858+ * context: useMemo(() => ({
5959+ * additionalTypenames: ['Item'],
6060+ * }), [])
6161+ * });
6262+ * ```
6363+ */
2764 context?: Partial<OperationContext>;
6565+ /** Prevents {@link useQuery} from automatically executing GraphQL query operations.
6666+ *
6767+ * @remarks
6868+ * `pause` may be set to `true` to stop {@link useQuery} from executing
6969+ * automatically. The hook will stop receiving updates from the {@link Client}
7070+ * and won’t execute the query operation, until either it’s set to `false`
7171+ * or the {@link UseQueryExecute} function is called.
7272+ *
7373+ * @see {@link https://urql.dev/goto/docs/basics/react-preact/#pausing-usequery} for
7474+ * documentation on the `pause` option.
7575+ */
2876 pause?: boolean;
2977} & GraphQLRequestParams<Data, Variables>;
30787979+/** State of the current query, your {@link useQuery} hook is executing.
8080+ *
8181+ * @remarks
8282+ * `UseQueryState` is returned (in a tuple) by {@link useQuery} and
8383+ * gives you the updating {@link OperationResult} of GraphQL queries.
8484+ *
8585+ * Even when the query and variables passed to {@link useQuery} change,
8686+ * this state preserves the prior state and sets the `fetching` flag to
8787+ * `true`.
8888+ * This allows you to display the previous state, while implementing
8989+ * a separate loading indicator separately.
9090+ */
3191export interface UseQueryState<
3292 Data = any,
3393 Variables extends AnyVariables = AnyVariables
3494> {
9595+ /** Indicates whether `useQuery` is waiting for a new result.
9696+ *
9797+ * @remarks
9898+ * When `useQuery` is passed a new query and/or variables, it will
9999+ * start executing the new query operation and `fetching` is set to
100100+ * `true` until a result arrives.
101101+ *
102102+ * Hint: This is subtly different than whether the query is actually
103103+ * fetching, and doesn’t indicate whether a query is being re-executed
104104+ * in the background. For this, see {@link UseQueryState.stale}.
105105+ */
35106 fetching: boolean;
107107+ /** Indicates that the state is not fresh and a new result will follow.
108108+ *
109109+ * @remarks
110110+ * The `stale` flag is set to `true` when a new result for the query
111111+ * is expected and `useQuery` is waiting for it. This may indicate that
112112+ * a new request is being requested in the background.
113113+ *
114114+ * @see {@link OperationResult.stale} for the source of this value.
115115+ */
36116 stale: boolean;
117117+ /** The {@link OperationResult.data} for the executed query. */
37118 data?: Data;
119119+ /** The {@link OperationResult.error} for the executed query. */
38120 error?: CombinedError;
121121+ /** The {@link OperationResult.extensions} for the executed query. */
39122 extensions?: Record<string, any>;
123123+ /** The {@link Operation} that the current state is for.
124124+ *
125125+ * @remarks
126126+ * This is the {@link Operation} that is currently being executed.
127127+ * When {@link UseQueryState.fetching} is `true`, this is the
128128+ * last `Operation` that the current state was for.
129129+ */
40130 operation?: Operation<Data, Variables>;
41131}
42132133133+/** Triggers {@link useQuery} to execute a new GraphQL query operation.
134134+ *
135135+ * @param opts - optionally, context options that will be merged with the hook's
136136+ * {@link UseQueryArgs.context} options and the `Client`’s options.
137137+ *
138138+ * @remarks
139139+ * When called, {@link useQuery} will re-execute the GraphQL query operation
140140+ * it currently holds, even if {@link UseQueryArgs.pause} is set to `true`.
141141+ *
142142+ * This is useful for executing a paused query or re-executing a query
143143+ * and get a new network result, by passing a new request policy.
144144+ *
145145+ * ```ts
146146+ * const [result, reexecuteQuery] = useQuery({ query });
147147+ *
148148+ * const refresh = () => {
149149+ * // Re-execute the query with a network-only policy, skipping the cache
150150+ * reexecuteQuery({ requestPolicy: 'network-only' });
151151+ * };
152152+ * ```
153153+ */
154154+export type UseQueryExecute = (opts?: Partial<OperationContext>) => void;
155155+156156+/** Result tuple returned by the {@link useQuery} hook.
157157+ *
158158+ * @remarks
159159+ * Similarly to a `useState` hook’s return value,
160160+ * the first element is the {@link useQuery}’s result and state,
161161+ * a {@link UseQueryState} object,
162162+ * and the second is used to imperatively re-execute the query
163163+ * via a {@link UseQueryExecute} function.
164164+ */
43165export type UseQueryResponse<
44166 Data = any,
45167 Variables extends AnyVariables = AnyVariables
4646-> = [
4747- UseQueryState<Data, Variables>,
4848- (opts?: Partial<OperationContext>) => void
4949-];
168168+> = [UseQueryState<Data, Variables>, UseQueryExecute];
5016951170const isSuspense = (client: Client, context?: Partial<OperationContext>) =>
52171 client.suspense && (!context || context.suspense !== false);
53172173173+/** Hook to run a GraphQL query and get updated GraphQL results.
174174+ *
175175+ * @param args - a {@link UseQueryArgs} object, to pass a `query`, `variables`, and options.
176176+ * @returns a {@link UseQueryResponse} tuple of a {@link UseQueryState} result, and re-execute function.
177177+ *
178178+ * @remarks
179179+ * `useQuery` allows GraphQL queries to be defined and executed.
180180+ * Given {@link UseQueryArgs.query}, it executes the GraphQL query with the
181181+ * context’s {@link Client}.
182182+ *
183183+ * The returned result updates when the `Client` has new results
184184+ * for the query, and changes when your input `args` change.
185185+ *
186186+ * Additionally, if the `suspense` option is enabled on the `Client`,
187187+ * the `useQuery` hook will suspend instead of indicating that it’s
188188+ * waiting for a result via {@link UseQueryState.fetching}.
189189+ *
190190+ * @see {@link https://urql.dev/goto/urql/docs/basics/react-preact/#queries} for `useQuery` docs.
191191+ *
192192+ * @example
193193+ * ```ts
194194+ * import { gql, useQuery } from 'urql';
195195+ *
196196+ * const TodosQuery = gql`
197197+ * query { todos { id, title } }
198198+ * `;
199199+ *
200200+ * const Todos = () => {
201201+ * const [result, reexecuteQuery] = useQuery({
202202+ * query: TodosQuery,
203203+ * variables: {},
204204+ * });
205205+ * // ...
206206+ * };
207207+ * ```
208208+ */
54209export function useQuery<
55210 Data = any,
56211 Variables extends AnyVariables = AnyVariables
+3-1
packages/react-urql/src/hooks/useRequest.ts
···77 createRequest,
88} from '@urql/core';
991010-/** Creates a request from a query and variables but preserves reference equality if the key isn't changing */
1010+/** Creates a request from a query and variables but preserves reference equality if the key isn't changing
1111+ * @internal
1212+ */
1113export function useRequest<
1214 Data = any,
1315 Variables extends AnyVariables = AnyVariables
+175-4
packages/react-urql/src/hooks/useSubscription.ts
···1515import { useRequest } from './useRequest';
1616import { initialState, computeNextState, hasDepsChanged } from './state';
17171818+/** Input arguments for the {@link useSubscription} hook.
1919+ *
2020+ * @param query - The GraphQL subscription document that `useSubscription` executes.
2121+ * @param variables - The variables for the GraphQL subscription that `useSubscription` executes.
2222+ */
1823export type UseSubscriptionArgs<
1924 Variables extends AnyVariables = AnyVariables,
2025 Data = any
2126> = {
2727+ /** Prevents {@link useSubscription} from automatically starting GraphQL subscriptions.
2828+ *
2929+ * @remarks
3030+ * `pause` may be set to `true` to stop {@link useSubscription} from starting its subscription
3131+ * automatically. The hook will stop receiving updates from the {@link Client}
3232+ * and won’t start the subscription operation, until either it’s set to `false`
3333+ * or the {@link UseSubscriptionExecute} function is called.
3434+ */
2235 pause?: boolean;
3636+ /** Updates the {@link OperationContext} for the executed GraphQL subscription operation.
3737+ *
3838+ * @remarks
3939+ * `context` may be passed to {@link useSubscription}, to update the {@link OperationContext}
4040+ * of a subscription operation. This may be used to update the `context` that exchanges
4141+ * will receive for a single hook.
4242+ *
4343+ * Hint: This should be wrapped in a `useMemo` hook, to make sure that your
4444+ * component doesn’t infinitely update.
4545+ *
4646+ * @example
4747+ * ```ts
4848+ * const [result, reexecute] = useSubscription({
4949+ * query,
5050+ * context: useMemo(() => ({
5151+ * additionalTypenames: ['Item'],
5252+ * }), [])
5353+ * });
5454+ * ```
5555+ */
2356 context?: Partial<OperationContext>;
2457} & GraphQLRequestParams<Data, Variables>;
25585959+/** Combines previous data with an incoming subscription result’s data.
6060+ *
6161+ * @remarks
6262+ * A `SubscriptionHandler` may be passed to {@link useSubscription} to
6363+ * aggregate subscription results into a combined {@link UseSubscriptionState.data}
6464+ * value.
6565+ *
6666+ * This is useful when a subscription event delivers a single item, while
6767+ * you’d like to display a list of events.
6868+ *
6969+ * @example
7070+ * ```ts
7171+ * const NotificationsSubscription = gql`
7272+ * subscription { newNotification { id, text } }
7373+ * `;
7474+ *
7575+ * const combineNotifications = (notifications = [], data) => {
7676+ * return [...notifications, data.newNotification];
7777+ * };
7878+ *
7979+ * const [result, executeSubscription] = useSubscription(
8080+ * { query: NotificationsSubscription },
8181+ * combineNotifications,
8282+ * );
8383+ * ```
8484+ */
2685export type SubscriptionHandler<T, R> = (prev: R | undefined, data: T) => R;
27868787+/** State of the current subscription, your {@link useSubscription} hook is executing.
8888+ *
8989+ * @remarks
9090+ * `UseSubscriptionState` is returned (in a tuple) by {@link useSubscription} and
9191+ * gives you the updating {@link OperationResult} of GraphQL subscriptions.
9292+ *
9393+ * If a {@link SubscriptionHandler} has been passed to `useSubscription` then
9494+ * {@link UseSubscriptionState.data} is instead the updated data as returned
9595+ * by the handler, otherwise it’s the latest result’s data.
9696+ *
9797+ * Hint: Even when the query and variables passed to {@link useSubscription} change,
9898+ * this state preserves the prior state.
9999+ */
28100export interface UseSubscriptionState<
29101 Data = any,
30102 Variables extends AnyVariables = AnyVariables
31103> {
104104+ /** Indicates whether `useSubscription`’s subscription is active.
105105+ *
106106+ * @remarks
107107+ * When `useSubscription` starts a subscription, the `fetching` flag
108108+ * is set to `true` and will remain `true` until the subscription
109109+ * completes on the API, or the {@link UseSubscriptionArgs.pause}
110110+ * flag is set to `true`.
111111+ */
32112 fetching: boolean;
113113+ /** Indicates that the subscription result is not fresh.
114114+ *
115115+ * @remarks
116116+ * This is mostly unused for subscriptions and will rarely affect you, and
117117+ * is more relevant for queries.
118118+ *
119119+ * @see {@link OperationResult.stale} for the source of this value.
120120+ */
33121 stale: boolean;
122122+ /** The {@link OperationResult.data} for the executed subscription, or data returned by a handler.
123123+ *
124124+ * @remarks
125125+ * `data` will be set to the last {@link OperationResult.data} value
126126+ * received for the subscription.
127127+ *
128128+ * It will instead be set to the values that {@link SubscriptionHandler}
129129+ * returned, if a handler has been passed to {@link useSubscription}.
130130+ */
34131 data?: Data;
132132+ /** The {@link OperationResult.error} for the executed subscription. */
35133 error?: CombinedError;
134134+ /** The {@link OperationResult.extensions} for the executed mutation. */
36135 extensions?: Record<string, any>;
136136+ /** The {@link Operation} that the current state is for.
137137+ *
138138+ * @remarks
139139+ * This is the subscription {@link Operation} that is currently active.
140140+ * When {@link UseSubscriptionState.fetching} is `true`, this is the
141141+ * last `Operation` that the current state was for.
142142+ */
37143 operation?: Operation<Data, Variables>;
38144}
39145146146+/** Triggers {@link useSubscription} to reexecute a GraphQL subscription operation.
147147+ *
148148+ * @param opts - optionally, context options that will be merged with the hook's
149149+ * {@link UseSubscriptionArgs.context} options and the `Client`’s options.
150150+ *
151151+ * @remarks
152152+ * When called, {@link useSubscription} will restart the GraphQL subscription
153153+ * operation it currently holds. If {@link UseSubscriptionArgs.pause} is set
154154+ * to `true`, it will start executing the subscription.
155155+ *
156156+ * ```ts
157157+ * const [result, executeSubscription] = useSubscription({
158158+ * query,
159159+ * pause: true,
160160+ * });
161161+ *
162162+ * const start = () => {
163163+ * executeSubscription();
164164+ * };
165165+ * ```
166166+ */
167167+export type UseSubscriptionExecute = (opts?: Partial<OperationContext>) => void;
168168+169169+/** Result tuple returned by the {@link useSubscription} hook.
170170+ *
171171+ * @remarks
172172+ * Similarly to a `useState` hook’s return value,
173173+ * the first element is the {@link useSubscription}’s state,
174174+ * a {@link UseSubscriptionState} object,
175175+ * and the second is used to imperatively re-execute or start the subscription
176176+ * via a {@link UseMutationExecute} function.
177177+ */
40178export type UseSubscriptionResponse<
41179 Data = any,
42180 Variables extends AnyVariables = AnyVariables
4343-> = [
4444- UseSubscriptionState<Data, Variables>,
4545- (opts?: Partial<OperationContext>) => void
4646-];
181181+> = [UseSubscriptionState<Data, Variables>, UseSubscriptionExecute];
47182183183+/** Hook to run a GraphQL subscription and get updated GraphQL results.
184184+ *
185185+ * @param args - a {@link UseSubscriptionArgs} object, to pass a `query`, `variables`, and options.
186186+ * @param handler - optionally, a {@link SubscriptionHandler} function to combine multiple subscription results.
187187+ * @returns a {@link UseSubscriptionResponse} tuple of a {@link UseSubscriptionState} result, and an execute function.
188188+ *
189189+ * @remarks
190190+ * `useSubscription` allows GraphQL subscriptions to be defined and executed.
191191+ * Given {@link UseSubscriptionArgs.query}, it executes the GraphQL subscription with the
192192+ * context’s {@link Client}.
193193+ *
194194+ * The returned result updates when the `Client` has new results
195195+ * for the subscription, and `data` is updated with the result’s data
196196+ * or with the `data` that a `handler` returns.
197197+ *
198198+ * @example
199199+ * ```ts
200200+ * import { gql, useSubscription } from 'urql';
201201+ *
202202+ * const NotificationsSubscription = gql`
203203+ * subscription { newNotification { id, text } }
204204+ * `;
205205+ *
206206+ * const combineNotifications = (notifications = [], data) => {
207207+ * return [...notifications, data.newNotification];
208208+ * };
209209+ *
210210+ * const Notifications = () => {
211211+ * const [result, executeSubscription] = useSubscription(
212212+ * { query: NotificationsSubscription },
213213+ * combineNotifications,
214214+ * );
215215+ * // ...
216216+ * };
217217+ * ```
218218+ */
48219export function useSubscription<
49220 Data = any,
50221 Result = Data,
+27-3
packages/storage-rn/src/makeAsyncStorage.ts
···22import AsyncStorage from '@react-native-async-storage/async-storage';
33import NetInfo from '@react-native-community/netinfo';
4455-export type StorageOptions = {
55+export interface StorageOptions {
66+ /** Name of the `AsyncStorage` key that’s used for persisted data.
77+ * @defaultValue `'graphcache-data'`
88+ */
69 dataKey?: string;
1010+ /** Name of the `AsyncStorage` key that’s used for persisted metadata.
1111+ * @defaultValue `'graphcache-metadata'`
1212+ */
713 metadataKey?: string;
88- maxAge?: number; // Number of days
99-};
1414+ /** Maximum age of cache entries (in days) after which data is discarded.
1515+ * @defaultValue `7` days
1616+ */
1717+ maxAge?: number;
1818+}
10191120const parseData = (persistedData: any, fallback: any) => {
1221 try {
···20292130let disconnect;
22313232+/** React Native storage adapter persisting to `AsyncStorage`. */
2333export interface DefaultAsyncStorage extends StorageAdapter {
3434+ /** Clears the entire `AsyncStorage`. */
2435 clear(): Promise<any>;
2536}
26373838+/** Creates a {@link StorageAdapter} which uses React Native’s `AsyncStorage`.
3939+ *
4040+ * @param opts - A {@link StorageOptions} configuration object.
4141+ * @returns the created {@link DefaultAsyncStorage} adapter.
4242+ *
4343+ * @remarks
4444+ * `makeAsyncStorage` creates a storage adapter for React Native,
4545+ * which persisted to `AsyncStorage` via the `@react-native-async-storage/async-storage`
4646+ * package.
4747+ *
4848+ * Note: We have no data on stability of this storage and our Offline Support
4949+ * for large APIs or longterm use. Proceed with caution.
5050+ */
2751export const makeAsyncStorage: (
2852 ops?: StorageOptions
2953) => DefaultAsyncStorage = ({
+64-1
packages/svelte-urql/src/common.ts
···22import type { AnyVariables, OperationResult } from '@urql/core';
33import { Source, make } from 'wonka';
4455+/** An {@link OperationResult} with an added {@link OperationResultState.fetching} flag.
66+ *
77+ * @remarks
88+ * Stores will contain a readable state based on {@link OperationResult | OperationResults}
99+ * they received.
1010+ */
511export interface OperationResultState<
612 Data = any,
713 Variables extends AnyVariables = AnyVariables
814> extends OperationResult<Data, Variables> {
1515+ /** Indicates whether the store is waiting for a new {@link OperationResult}.
1616+ *
1717+ * @remarks
1818+ * When a store starts executing a GraphQL operation, `fetching` is
1919+ * set to `true` until a result arrives.
2020+ *
2121+ * Hint: This is subtly different than whether the operation is actually
2222+ * fetching, and doesn’t indicate whether an operation is being re-executed
2323+ * in the background. For this, see {@link OperationResult.stale}.
2424+ */
925 fetching: boolean;
1026}
11271212-/** A Readable containing an `OperationResult` with a fetching flag. */
2828+/** A Readable store of {@link OperationResultState}. */
1329export type OperationResultStore<
1430 Data = any,
1531 Variables extends AnyVariables = AnyVariables
1632> = Readable<OperationResultState<Data, Variables>>;
17333434+/** Consumes a {@link Readable} as a {@link Source}.
3535+ * @internal
3636+ */
1837export const fromStore = <T>(store$: Readable<T>): Source<T> =>
1938 make(observer => store$.subscribe(observer.next));
2039···2847 stale: false,
2948};
30495050+/** A pausable Svelte store.
5151+ *
5252+ * @remarks
5353+ * The {@link queryStore} and {@link useSubscription} store allow
5454+ * you to pause execution and resume it later on, which is managed
5555+ * by a `pause` option passed to them.
5656+ *
5757+ * A `Pauseable` allows execution of GraphQL operations to be paused,
5858+ * which means a {@link OperationResultStore} won’t update with new
5959+ * results or execute new operations, and to be resumed later on.
6060+ */
3161export interface Pausable {
6262+ /** Indicates whether a store is currently paused.
6363+ *
6464+ * @remarks
6565+ * When a {@link OperationResultStore} has been paused, it will stop
6666+ * receiving updates from the {@link Client} and won’t execute GraphQL
6767+ * operations, until this writable becomes `true` or
6868+ * {@link Pausable.resume} is called.
6969+ *
7070+ * @see {@link https://urql.dev/goto/docs/basics/svelte#pausing-queries} for
7171+ * documentation on the `Pausable`.
7272+ */
3273 isPaused$: Writable<boolean>;
7474+ /** Pauses a GraphQL operation to stop it from executing.
7575+ *
7676+ * @remarks
7777+ * Pauses an {@link OperationResultStore}’s GraphQL operation, which
7878+ * stops it from receiving updates from the {@link Client} and to stop
7979+ * an ongoing operation.
8080+ *
8181+ * @see {@link https://urql.dev/goto/docs/basics/svelte#pausing-queries} for
8282+ * documentation on the `Pausable`.
8383+ */
3384 pause(): void;
8585+ /** Resumes a paused GraphQL operation if it’s currently paused.
8686+ *
8787+ * @remarks
8888+ * Resumes or starts {@link OperationResultStore}’s GraphQL operation,
8989+ * if it’s currently paused.
9090+ *
9191+ * @see {@link https://urql.dev/goto/docs/basics/svelte#pausing-queries} for
9292+ * documentation on the `Pausable`.
9393+ */
3494 resume(): void;
3595}
36969797+/** Creates a {@link Pausable}.
9898+ * @internal
9999+ */
37100export const createPausable = (isPaused$: Writable<boolean>): Pausable => ({
38101 isPaused$,
39102 pause() {
+32-3
packages/svelte-urql/src/context.ts
···3344const _contextKey = '$$_urql';
5566-/** Retrieves a Client from Svelte's context */
66+/** Returns a provided {@link Client}.
77+ *
88+ * @remarks
99+ * `getContextClient` returns the {@link Client} that’s previously
1010+ * been provided on Svelte’s context with {@link setContextClient}.
1111+ *
1212+ * This is useful to create a `Client` on Svelte’s context once, and
1313+ * then pass it to all GraphQL store functions without importing it
1414+ * from a singleton export.
1515+ *
1616+ * @throws
1717+ * In development, if `getContextClient` can’t get a {@link Client}
1818+ * from Svelte’s context, an error will be thrown.
1919+ */
720export const getContextClient = (): Client => {
821 const client = getContext(_contextKey);
922 if (process.env.NODE_ENV !== 'production' && !client) {
···1528 return client as Client;
1629};
17301818-/** Sets a Client on Svelte's context */
3131+/** Provides a {@link Client} to a component’s children.
3232+ *
3333+ * @remarks
3434+ * `setContextClient` updates the Svelte context to provide
3535+ * a {@link Client} to be later retrieved using the
3636+ * {@link getContextClient} function.
3737+ */
1938export const setContextClient = (client: Client): void => {
2039 setContext(_contextKey, client);
2140};
22412323-/** Creates Client and adds it to Svelte's context */
4242+/** Creates a {@link Client} and provides it to a component’s children.
4343+ *
4444+ * @param args - a {@link ClientOptions} object to create a `Client` with.
4545+ * @returns the created {@link Client}.
4646+ *
4747+ * @remarks
4848+ * `initContextClient` is a convenience wrapper around
4949+ * `setContextClient` that accepts {@link ClientOptions},
5050+ * creates a {@link Client} and provides it to be later
5151+ * retrieved using the {@link getContextClient} function.
5252+ */
2453export const initContextClient = (args: ClientOptions): Client => {
2554 const client = new Client(args);
2655 setContextClient(client);
+7
packages/svelte-urql/src/index.ts
···11export * from '@urql/core';
22+33+export type {
44+ Pausable,
55+ OperationResultStore,
66+ OperationResultState,
77+} from './common';
88+29export * from './queryStore';
310export * from './mutationStore';
411export * from './subscriptionStore';
+67
packages/svelte-urql/src/mutationStore.ts
···1515 initialResult,
1616} from './common';
17171818+/** Input arguments for the {@link mutationStore} function.
1919+ *
2020+ * @param query - The GraphQL mutation that the `mutationStore` executes.
2121+ * @param variables - The variables for the GraphQL mutation that `mutationStore` executes.
2222+ */
1823export type MutationArgs<
1924 Data = any,
2025 Variables extends AnyVariables = AnyVariables
2126> = {
2727+ /** The {@link Client} using which the subscription will be started.
2828+ *
2929+ * @remarks
3030+ * If you’ve previously provided a {@link Client} on Svelte’s context
3131+ * this can be set to {@link getContextClient}’s return value.
3232+ */
2233 client: Client;
3434+ /** Updates the {@link OperationContext} for the GraphQL mutation operation.
3535+ *
3636+ * @remarks
3737+ * `context` may be passed to {@link mutationStore}, to update the
3838+ * {@link OperationContext} of a mutation operation. This may be used to update
3939+ * the `context` that exchanges will receive for a single hook.
4040+ *
4141+ * @example
4242+ * ```ts
4343+ * mutationStore({
4444+ * query,
4545+ * context: {
4646+ * additionalTypenames: ['Item'],
4747+ * },
4848+ * });
4949+ * ```
5050+ */
2351 context?: Partial<OperationContext>;
2452} & GraphQLRequestParams<Data, Variables>;
25535454+/** Function to create a `mutationStore` that runs a GraphQL mutation and updates with a GraphQL result.
5555+ *
5656+ * @param args - a {@link MutationArgs} object, to pass a `query`, `variables`, and options.
5757+ * @returns a {@link OperationResultStore} of the mutation’s result.
5858+ *
5959+ * @remarks
6060+ * `mutationStore` allows a GraphQL mutation to be defined as a Svelte store.
6161+ * Given {@link MutationArgs.query}, it executes the GraphQL mutation on the
6262+ * {@link MutationArgs.client}.
6363+ *
6464+ * The returned store updates with an {@link OperationResult} when
6565+ * the `Client` returns a result for the mutation.
6666+ *
6767+ * Hint: It’s often easier to use {@link Client.mutation} if you’re
6868+ * creating a mutation imperatively and don’t need a store.
6969+ *
7070+ * @see {@link https://urql.dev/goto/docs/basics/svelte#mutations} for
7171+ * `mutationStore` docs.
7272+ *
7373+ * @example
7474+ * ```ts
7575+ * import { mutationStore, gql, getContextClient } from '@urql/svelte';
7676+ *
7777+ * const client = getContextClient();
7878+ *
7979+ * let result;
8080+ * function updateTodo({ id, title }) {
8181+ * result = queryStore({
8282+ * client,
8383+ * query: gql`
8484+ * mutation($id: ID!, $title: String!) {
8585+ * updateTodo(id: $id, title: $title) { id, title }
8686+ * }
8787+ * `,
8888+ * variables: { id, title },
8989+ * });
9090+ * }
9191+ * ```
9292+ */
2693export function mutationStore<
2794 Data = any,
2895 Variables extends AnyVariables = AnyVariables
+76
packages/svelte-urql/src/queryStore.ts
···3030 fromStore,
3131} from './common';
32323333+/** Input arguments for the {@link queryStore} function.
3434+ *
3535+ * @param query - The GraphQL query that the `queryStore` executes.
3636+ * @param variables - The variables for the GraphQL query that `queryStore` executes.
3737+ */
3338export type QueryArgs<
3439 Data = any,
3540 Variables extends AnyVariables = AnyVariables
3641> = {
4242+ /** The {@link Client} using which the query will be executed.
4343+ *
4444+ * @remarks
4545+ * If you’ve previously provided a {@link Client} on Svelte’s context
4646+ * this can be set to {@link getContextClient}’s return value.
4747+ */
3748 client: Client;
4949+ /** Updates the {@link OperationContext} for the executed GraphQL query operation.
5050+ *
5151+ * @remarks
5252+ * `context` may be passed to {@link queryStore}, to update the {@link OperationContext}
5353+ * of a query operation. This may be used to update the `context` that exchanges
5454+ * will receive for a single hook.
5555+ *
5656+ * @example
5757+ * ```ts
5858+ * queryStore({
5959+ * query,
6060+ * context: {
6161+ * additionalTypenames: ['Item'],
6262+ * },
6363+ * });
6464+ * ```
6565+ */
3866 context?: Partial<OperationContext>;
6767+ /** Sets the {@link RequestPolicy} for the executed GraphQL query operation.
6868+ *
6969+ * @remarks
7070+ * `requestPolicy` modifies the {@link RequestPolicy} of the GraphQL query operation
7171+ * that the {@link queryStore} executes, and indicates a caching strategy for cache exchanges.
7272+ *
7373+ * For example, when set to `'cache-and-network'`, the `queryStore` will
7474+ * receive a cached result with `stale: true` and an API request will be
7575+ * sent in the background.
7676+ *
7777+ * @see {@link OperationContext.requestPolicy} for where this value is set.
7878+ */
3979 requestPolicy?: RequestPolicy;
8080+ /** Prevents the {@link queryStore} from automatically executing GraphQL query operations.
8181+ *
8282+ * @remarks
8383+ * `pause` may be set to `true` to stop the {@link queryStore} from executing
8484+ * automatically. The store will stop receiving updates from the {@link Client}
8585+ * and won’t execute the query operation, until either it’s set to `false`
8686+ * or {@link Pausable.resume} is called.
8787+ *
8888+ * @see {@link https://urql.dev/goto/docs/basics/svelte#pausing-queries} for
8989+ * documentation on the `pause` option.
9090+ */
4091 pause?: boolean;
4192} & GraphQLRequestParams<Data, Variables>;
42939494+/** Function to create a `queryStore` that runs a GraphQL query and updates with GraphQL results.
9595+ *
9696+ * @param args - a {@link QueryArgs} object, to pass a `query`, `variables`, and options.
9797+ * @returns a {@link OperationResultStore} of query results, which implements {@link Pausable}.
9898+ *
9999+ * @remarks
100100+ * `queryStore` allows GraphQL queries to be defined as Svelte stores.
101101+ * Given {@link QueryArgs.query}, it executes the GraphQL query on the
102102+ * {@link QueryArgs.client}.
103103+ *
104104+ * The returned store updates with {@link OperationResult} values when
105105+ * the `Client` has new results for the query.
106106+ *
107107+ * @see {@link https://urql.dev/goto/docs/basics/svelte#queries} for `queryStore` docs.
108108+ *
109109+ * @example
110110+ * ```ts
111111+ * import { queryStore, gql, getContextClient } from '@urql/svelte';
112112+ *
113113+ * const todos = queryStore({
114114+ * client: getContextClient(),
115115+ * query: gql`{ todos { id, title } }`,
116116+ * });
117117+ * ```
118118+ */
43119export function queryStore<
44120 Data = any,
45121 Variables extends AnyVariables = AnyVariables
+93
packages/svelte-urql/src/subscriptionStore.ts
···2929 fromStore,
3030} from './common';
31313232+/** Combines previous data with an incoming subscription result’s data.
3333+ *
3434+ * @remarks
3535+ * A `SubscriptionHandler` may be passed to {@link subscriptionStore} to
3636+ * aggregate subscription results into a combined `data` value on the
3737+ * {@link OperationResultStore}.
3838+ *
3939+ * This is useful when a subscription event delivers a single item, while
4040+ * you’d like to display a list of events.
4141+ *
4242+ * @example
4343+ * ```ts
4444+ * const NotificationsSubscription = gql`
4545+ * subscription { newNotification { id, text } }
4646+ * `;
4747+ *
4848+ * subscriptionStore(
4949+ * { query: NotificationsSubscription },
5050+ * function combineNotifications(notifications = [], data) {
5151+ * return [...notifications, data.newNotification];
5252+ * },
5353+ * );
5454+ * ```
5555+ */
3256export type SubscriptionHandler<T, R> = (prev: R | undefined, data: T) => R;
33575858+/** Input arguments for the {@link subscriptionStore} function.
5959+ *
6060+ * @param query - The GraphQL subscription that the `subscriptionStore` executes.
6161+ * @param variables - The variables for the GraphQL subscription that `subscriptionStore` executes.
6262+ */
3463export type SubscriptionArgs<
3564 Data = any,
3665 Variables extends AnyVariables = AnyVariables
3766> = {
6767+ /** The {@link Client} using which the subscription will be started.
6868+ *
6969+ * @remarks
7070+ * If you’ve previously provided a {@link Client} on Svelte’s context
7171+ * this can be set to {@link getContextClient}’s return value.
7272+ */
3873 client: Client;
7474+ /** Updates the {@link OperationContext} for the GraphQL subscription operation.
7575+ *
7676+ * @remarks
7777+ * `context` may be passed to {@link subscriptionStore}, to update the
7878+ * {@link OperationContext} of a subscription operation. This may be used to update
7979+ * the `context` that exchanges will receive for a single hook.
8080+ *
8181+ * @example
8282+ * ```ts
8383+ * subscriptionStore({
8484+ * query,
8585+ * context: {
8686+ * additionalTypenames: ['Item'],
8787+ * },
8888+ * });
8989+ * ```
9090+ */
3991 context?: Partial<OperationContext>;
9292+ /** Prevents the {@link subscriptionStore} from automatically starting the GraphQL subscription.
9393+ *
9494+ * @remarks
9595+ * `pause` may be set to `true` to stop the {@link subscriptionStore} from starting
9696+ * its subscription automatically. The store won't execute the subscription operation,
9797+ * until either it’s set to `false` or {@link Pausable.resume} is called.
9898+ */
4099 pause?: boolean;
41100} & GraphQLRequestParams<Data, Variables>;
42101102102+/** Function to create a `subscriptionStore` that starts a GraphQL subscription.
103103+ *
104104+ * @param args - a {@link QueryArgs} object, to pass a `query`, `variables`, and options.
105105+ * @param handler - optionally, a {@link SubscriptionHandler} function to combine multiple subscription results.
106106+ * @returns a {@link OperationResultStore} of subscription results, which implements {@link Pausable}.
107107+ *
108108+ * @remarks
109109+ * `subscriptionStore` allows GraphQL subscriptions to be defined as Svelte stores.
110110+ * Given {@link SubscriptionArgs.query}, it executes the GraphQL subsription on the
111111+ * {@link SubscriptionArgs.client}.
112112+ *
113113+ * The returned store updates with {@link OperationResult} values when
114114+ * the `Client` has new results for the subscription.
115115+ *
116116+ * @see {@link https://urql.dev/goto/docs/advanced/subscriptions#svelte} for
117117+ * `subscriptionStore` docs.
118118+ *
119119+ * @example
120120+ * ```ts
121121+ * import { subscriptionStore, gql, getContextClient } from '@urql/svelte';
122122+ *
123123+ * const todos = subscriptionStore({
124124+ * client: getContextClient(),
125125+ * query: gql`
126126+ * subscription {
127127+ * newNotification { id, text }
128128+ * }
129129+ * `,
130130+ * function combineNotifications(notifications = [], data) {
131131+ * return [...notifications, data.newNotification];
132132+ * },
133133+ * });
134134+ * ```
135135+ */
43136export function subscriptionStore<
44137 Data,
45138 Result = Data,
+1-2
packages/vue-urql/src/index.ts
···1212export type {
1313 UseSubscriptionArgs,
1414 UseSubscriptionResponse,
1515- UseSubscriptionState,
1615 SubscriptionHandlerArg,
1716 SubscriptionHandler,
1817} from './useSubscription';
19182019export { useMutation } from './useMutation';
21202222-export type { UseMutationResponse, UseMutationState } from './useMutation';
2121+export type { UseMutationResponse } from './useMutation';
23222423import { install } from './useClient';
2524
+65
packages/vue-urql/src/useClient.ts
···3344const clientsPerInstance = new WeakMap<{}, Ref<Client>>();
5566+/** Provides a {@link Client} to a component’s children.
77+ *
88+ * @param opts - {@link ClientOptions}, a {@link Client}, or a reactive ref object of a `Client`.
99+ *
1010+ * @remarks
1111+ * `provideClient` provides a {@link Client} to `@urql/vue`’s GraphQL
1212+ * functions in children components.
1313+ *
1414+ * Hint: GraphQL functions and {@link useClient} will see the
1515+ * provided `Client`, even if `provideClient` has been called
1616+ * in the same component’s `setup` function.
1717+ *
1818+ * @example
1919+ * ```ts
2020+ * import { provideClient } from '@urql/vue';
2121+ * // All of `@urql/core` is also re-exported by `@urql/vue`:
2222+ * import { Client, cacheExchange, fetchExchange } from '@urql/core';
2323+ *
2424+ * export default {
2525+ * setup() {
2626+ * provideClient(new Client({
2727+ * url: 'https://API',
2828+ * exchanges: [cacheExchange, fetchExchange],
2929+ * }));
3030+ * },
3131+ * };
3232+ * ```
3333+ */
634export function provideClient(opts: ClientOptions | Client | Ref<Client>) {
735 let client: Ref<Client>;
836 if (!isRef(opts)) {
···2048 return client.value;
2149}
22505151+/** Provides a {@link Client} to a Vue app.
5252+ *
5353+ * @param app - the Vue {@link App}
5454+ * @param opts - {@link ClientOptions}, a {@link Client}, or a reactive ref object of a `Client`.
5555+ *
5656+ * @remarks
5757+ * `install` provides a {@link Client} to `@urql/vue`’s GraphQL
5858+ * functions in a Vue app.
5959+ *
6060+ * @example
6161+ * ```ts
6262+ * import * as urql from '@urql/vue';
6363+ * // All of `@urql/core` is also re-exported by `@urql/vue`:
6464+ * import { cacheExchange, fetchExchange } from '@urql/core';
6565+ *
6666+ * import { createApp } from 'vue';
6767+ * import Root from './App.vue';
6868+ *
6969+ * const app = createApp(Root);
7070+ * app.use(urql, {
7171+ * url: 'http://localhost:3000/graphql',
7272+ * exchanges: [cacheExchange, fetchExchange],
7373+ * });
7474+ * ```
7575+ */
2376export function install(app: App, opts: ClientOptions | Client | Ref<Client>) {
2477 let client: Ref<Client>;
2578 if (!isRef(opts)) {
···3083 app.provide('$urql', client);
3184}
32858686+/** Returns a provided reactive ref object of a {@link Client}.
8787+ *
8888+ * @remarks
8989+ * `useClient` may be called in Vue `setup` functions to retrieve a
9090+ * reactive rev object of a {@link Client} that’s previously been
9191+ * provided with {@link provideClient} in the current or a parent’s
9292+ * `setup` function.
9393+ *
9494+ * @throws
9595+ * In development, if `useClient` is called outside of a Vue `setup`
9696+ * function or no {@link Client} was provided, an error will be thrown.
9797+ */
3398export function useClient(): Ref<Client> {
3499 const instance = getCurrentInstance();
35100 if (process.env.NODE_ENV !== 'production' && !instance) {
+92
packages/vue-urql/src/useClientHandle.ts
···2020 UseSubscriptionResponse,
2121} from './useSubscription';
22222323+/** Handle to create GraphQL operations outside of Vue’s `setup` functions.
2424+ *
2525+ * @remarks
2626+ * The `ClientHandle` object is created inside a Vue `setup` function but
2727+ * allows its methods to be called outside of `setup` functions, delaying
2828+ * the creation of GraphQL operations, as an alternative to pausing queries
2929+ * or subscriptions.
3030+ *
3131+ * This is also important when chaining multiple functions inside an
3232+ * `async setup()` function.
3333+ *
3434+ * Hint: If you only need a single, non-updating result and want to execute
3535+ * queries programmatically, it may be easier to call the {@link Client.query}
3636+ * method.
3737+ */
2338export interface ClientHandle {
3939+ /** The {@link Client} that’ll be used to execute GraphQL operations. */
2440 client: Client;
25414242+ /** Calls {@link useQuery} outside of a synchronous Vue `setup` function.
4343+ *
4444+ * @param args - a {@link UseQueryArgs} object, to pass a `query`, `variables`, and options.
4545+ * @returns a {@link UseQueryResponse} object.
4646+ *
4747+ * @remarks
4848+ * Creates a {@link UseQueryResponse} outside of a synchronous Vue `setup`
4949+ * function or when chained in an `async setup()` function.
5050+ */
2651 useQuery<T = any, V extends AnyVariables = AnyVariables>(
2752 args: UseQueryArgs<T, V>
2853 ): UseQueryResponse<T, V>;
29545555+ /** Calls {@link useSubscription} outside of a synchronous Vue `setup` function.
5656+ *
5757+ * @param args - a {@link UseSubscriptionArgs} object, to pass a `query`, `variables`, and options.
5858+ * @param handler - optionally, a {@link SubscriptionHandler} function to combine multiple subscription results.
5959+ * @returns a {@link UseSubscriptionResponse} object.
6060+ *
6161+ * @remarks
6262+ * Creates a {@link UseSubscriptionResponse} outside of a synchronous Vue `setup`
6363+ * function or when chained in an `async setup()` function.
6464+ */
3065 useSubscription<T = any, R = T, V extends AnyVariables = AnyVariables>(
3166 args: UseSubscriptionArgs<T, V>,
3267 handler?: SubscriptionHandlerArg<T, R>
3368 ): UseSubscriptionResponse<T, R, V>;
34697070+ /** Calls {@link useMutation} outside of a synchronous Vue `setup` function.
7171+ *
7272+ * @param query - a GraphQL mutation document which `useMutation` will execute.
7373+ * @returns a {@link UseMutationResponse} object.
7474+ *
7575+ * @remarks
7676+ * Creates a {@link UseMutationResponse} outside of a synchronous Vue `setup`
7777+ * function or when chained in an `async setup()` function.
7878+ */
3579 useMutation<T = any, V extends AnyVariables = AnyVariables>(
3680 query: TypedDocumentNode<T, V> | DocumentNode | string
3781 ): UseMutationResponse<T, V>;
3882}
39838484+/** Creates a {@link ClientHandle} inside a Vue `setup` function.
8585+ *
8686+ * @remarks
8787+ * `useClientHandle` creates and returns a {@link ClientHandle}
8888+ * when called in a Vue `setup` function, which allows queries,
8989+ * mutations, and subscriptions to be created _outside_ of
9090+ * `setup` functions.
9191+ *
9292+ * This is also important when chaining multiple functions inside an
9393+ * `async setup()` function.
9494+ *
9595+ * {@link useQuery} and other GraphQL functions must usually
9696+ * be created in Vue `setup` functions so they can stop GraphQL
9797+ * operations when your component unmounts. However, while they
9898+ * queries and subscriptions can be paused, sometimes it’s easier
9999+ * to delay the creation of their response objects.
100100+ *
101101+ *
102102+ * @example
103103+ * ```ts
104104+ * import { ref, computed } from 'vue';
105105+ * import { gql, useClientHandle } from '@urql/vue';
106106+ *
107107+ * export default {
108108+ * async setup() {
109109+ * const handle = useClientHandle();
110110+ *
111111+ * const pokemons = await handle.useQuery({
112112+ * query: gql`{ pokemons(limit: 10) { id, name } }`,
113113+ * });
114114+ *
115115+ * const index = ref(0);
116116+ *
117117+ * // The `handle` allows another `useQuery` call to now be setup again
118118+ * const pokemon = await handle.useQuery({
119119+ * query: gql`
120120+ * query ($id: ID!) {
121121+ * pokemon(id: $id) { id, name }
122122+ * }
123123+ * `,
124124+ * variables: computed(() => ({
125125+ * id: pokemons.data.value.pokemons[index.value].id,
126126+ * }),
127127+ * });
128128+ * }
129129+ * };
130130+ * ```
131131+ */
40132export function useClientHandle(): ClientHandle {
41133 const client = useClient();
42134 const stops: WatchStopHandle[] = [];
+95-8
packages/vue-urql/src/useMutation.ts
···1818import { useClient } from './useClient';
1919import { unwrapPossibleProxy } from './utils';
20202121-export interface UseMutationState<T, V extends AnyVariables = AnyVariables> {
2121+/** State of the last mutation executed by {@link useMutation}.
2222+ *
2323+ * @remarks
2424+ * `UseMutationResponse` is returned by {@link useMutation} and
2525+ * gives you the {@link OperationResult} of the last executed mutation,
2626+ * and a {@link UseMutationResponse.executeMutation} method to
2727+ * start mutations.
2828+ *
2929+ * Even if the mutation document passed to {@link useMutation} changes,
3030+ * the state isn’t reset, so you can keep displaying the previous result.
3131+ */
3232+export interface UseMutationResponse<T, V extends AnyVariables = AnyVariables> {
3333+ /** Indicates whether `useMutation` is currently executing a mutation. */
2234 fetching: Ref<boolean>;
3535+ /** Indicates that the mutation result is not fresh.
3636+ *
3737+ * @remarks
3838+ * The `stale` flag is set to `true` when a new result for the mutation
3939+ * is expected.
4040+ * This is mostly unused for mutations and will rarely affect you, and
4141+ * is more relevant for queries.
4242+ *
4343+ * @see {@link OperationResult.stale} for the source of this value.
4444+ */
2345 stale: Ref<boolean>;
4646+ /** Reactive {@link OperationResult.data} for the executed mutation. */
2447 data: Ref<T | undefined>;
4848+ /** Reactive {@link OperationResult.error} for the executed mutation. */
2549 error: Ref<CombinedError | undefined>;
5050+ /** Reactive {@link OperationResult.extensions} for the executed mutation. */
2651 extensions: Ref<Record<string, any> | undefined>;
5252+ /** Reactive {@link Operation} that the current state is for.
5353+ *
5454+ * @remarks
5555+ * This is the mutation {@link Operation} that has last been executed.
5656+ * When {@link UseQueryState.fetching} is `true`, this is the
5757+ * last `Operation` that the current state was for.
5858+ */
2759 operation: Ref<Operation<T, V> | undefined>;
2828- executeMutation: (
6060+ /** Triggers {@link useMutation} to execute its GraphQL mutation operation.
6161+ *
6262+ * @param variables - variables using which the mutation will be executed.
6363+ * @param context - optionally, context options that will be merged with
6464+ * {@link UseMutationArgs.context} and the `Client`’s options.
6565+ * @returns the {@link OperationResult} of the mutation.
6666+ *
6767+ * @remarks
6868+ * When called, {@link useMutation} will start the GraphQL mutation
6969+ * it currently holds and use the `variables` passed to it.
7070+ *
7171+ * Once the mutation response comes back from the API, its
7272+ * returned promise will resolve to the mutation’s {@link OperationResult}
7373+ * and the {@link UseMutationResponse} will be updated with the result.
7474+ *
7575+ * @example
7676+ * ```ts
7777+ * const result = useMutation(UpdateTodo);
7878+ * const start = async ({ id, title }) => {
7979+ * const result = await result.executeMutation({ id, title });
8080+ * };
8181+ */
8282+ executeMutation(
2983 variables: V,
3084 context?: Partial<OperationContext>
3131- ) => Promise<OperationResult<T>>;
8585+ ): Promise<OperationResult<T>>;
3286}
33873434-export type UseMutationResponse<
3535- T,
3636- V extends AnyVariables = AnyVariables
3737-> = UseMutationState<T, V>;
3838-8888+/** Function to create a GraphQL mutation, run by passing variables to {@link UseMutationResponse.executeMutation}
8989+ *
9090+ * @param query - a GraphQL mutation document which `useMutation` will execute.
9191+ * @returns a {@link UseMutationResponse} object.
9292+ *
9393+ * @remarks
9494+ * `useMutation` allows GraphQL mutations to be defined inside Vue `setup` functions,
9595+ * and keeps its state after the mutation is started. Mutations can be started by calling
9696+ * {@link UseMutationResponse.executeMutation} with variables.
9797+ *
9898+ * The returned result updates when a mutation is executed and keeps
9999+ * track of the last mutation result.
100100+ *
101101+ * @see {@link https://urql.dev/goto/docs/basics/vue#mutations} for `useMutation` docs.
102102+ *
103103+ * @example
104104+ * ```ts
105105+ * import { gql, useMutation } from '@urql/vue';
106106+ *
107107+ * const UpdateTodo = gql`
108108+ * mutation ($id: ID!, $title: String!) {
109109+ * updateTodo(id: $id, title: $title) {
110110+ * id, title
111111+ * }
112112+ * }
113113+ * `;
114114+ *
115115+ * export default {
116116+ * setup() {
117117+ * const result = useMutation(UpdateTodo);
118118+ * const start = async ({ id, title }) => {
119119+ * const result = await result.executeMutation({ id, title });
120120+ * };
121121+ * // ...
122122+ * },
123123+ * };
124124+ * ```
125125+ */
39126export function useMutation<T = any, V extends AnyVariables = AnyVariables>(
40127 query: TypedDocumentNode<T, V> | DocumentNode | string
41128): UseMutationResponse<T, V> {
+180-5
packages/vue-urql/src/useQuery.ts
···2323type MaybeRef<T> = T | Ref<T>;
2424type MaybeRefObj<T extends {}> = { [K in keyof T]: MaybeRef<T[K]> };
25252626+/** Input arguments for the {@link useQuery} function.
2727+ *
2828+ * @param query - The GraphQL query that `useQuery` executes.
2929+ * @param variables - The variables for the GraphQL query that `useQuery` executes.
3030+ */
2631export type UseQueryArgs<
2732 Data = any,
2833 Variables extends AnyVariables = AnyVariables
2934> = {
3535+ /** Updates the {@link RequestPolicy} for the executed GraphQL query operation.
3636+ *
3737+ * @remarks
3838+ * `requestPolicy` modifies the {@link RequestPolicy} of the GraphQL query operation
3939+ * that `useQuery` executes, and indicates a caching strategy for cache exchanges.
4040+ *
4141+ * For example, when set to `'cache-and-network'`, {@link useQuery} will
4242+ * receive a cached result with `stale: true` and an API request will be
4343+ * sent in the background.
4444+ *
4545+ * @see {@link OperationContext.requestPolicy} for where this value is set.
4646+ */
3047 requestPolicy?: MaybeRef<RequestPolicy>;
4848+ /** Updates the {@link OperationContext} for the executed GraphQL query operation.
4949+ *
5050+ * @remarks
5151+ * `context` may be passed to {@link useQuery}, to update the {@link OperationContext}
5252+ * of a query operation. This may be used to update the `context` that exchanges
5353+ * will receive for a single hook.
5454+ *
5555+ * @example
5656+ * ```ts
5757+ * const result = useQuery({
5858+ * query,
5959+ * context: {
6060+ * additionalTypenames: ['Item'],
6161+ * },
6262+ * });
6363+ * ```
6464+ */
3165 context?: MaybeRef<Partial<OperationContext>>;
6666+ /** Prevents {@link useQuery} from automatically executing GraphQL query operations.
6767+ *
6868+ * @remarks
6969+ * `pause` may be set to `true` to stop {@link useQuery} from executing
7070+ * automatically. This will pause the query until {@link UseQueryState.resume}
7171+ * is called, or, if `pause` is a reactive ref of a boolean, until this
7272+ * ref changes to `true`.
7373+ *
7474+ * @see {@link https://urql.dev/goto/docs/basics/vue#pausing-usequery} for
7575+ * documentation on the `pause` option.
7676+ */
3277 pause?: MaybeRef<boolean>;
3378} & MaybeRefObj<GraphQLRequestParams<Data, Variables>>;
34793535-export type QueryPartialState<
3636- T = any,
3737- V extends AnyVariables = AnyVariables
3838-> = Partial<OperationResult<T, V>> & { fetching?: boolean };
3939-8080+/** State of the current query, your {@link useQuery} function is executing.
8181+ *
8282+ * @remarks
8383+ * `UseQueryState` is returned by {@link useQuery} and
8484+ * gives you the updating {@link OperationResult} of
8585+ * GraphQL queries.
8686+ *
8787+ * Each value that is part of the result is wrapped in a reactive ref
8888+ * and updates as results come in.
8989+ *
9090+ * Hint: Even when the query and variables update, the previous state of
9191+ * the last result is preserved, which allows you to display the
9292+ * previous state, while implementing a loading indicator separately.
9393+ */
4094export interface UseQueryState<T = any, V extends AnyVariables = AnyVariables> {
9595+ /** Indicates whether `useQuery` is waiting for a new result.
9696+ *
9797+ * @remarks
9898+ * When `useQuery` receives a new query and/or variables, it will
9999+ * start executing the new query operation and `fetching` is set to
100100+ * `true` until a result arrives.
101101+ *
102102+ * Hint: This is subtly different than whether the query is actually
103103+ * fetching, and doesn’t indicate whether a query is being re-executed
104104+ * in the background. For this, see {@link UseQueryState.stale}.
105105+ */
41106 fetching: Ref<boolean>;
107107+ /** Indicates that the state is not fresh and a new result will follow.
108108+ *
109109+ * @remarks
110110+ * The `stale` flag is set to `true` when a new result for the query
111111+ * is expected and `useQuery` is waiting for it. This may indicate that
112112+ * a new request is being requested in the background.
113113+ *
114114+ * @see {@link OperationResult.stale} for the source of this value.
115115+ */
42116 stale: Ref<boolean>;
117117+ /** Reactive {@link OperationResult.data} for the executed query. */
43118 data: Ref<T | undefined>;
119119+ /** Reactive {@link OperationResult.error} for the executed query. */
44120 error: Ref<CombinedError | undefined>;
121121+ /** Reactive {@link OperationResult.extensions} for the executed query. */
45122 extensions: Ref<Record<string, any> | undefined>;
123123+ /** Reactive {@link Operation} that the current state is for.
124124+ *
125125+ * @remarks
126126+ * This is the {@link Operation} that is currently being executed.
127127+ * When {@link UseQueryState.fetching} is `true`, this is the
128128+ * last `Operation` that the current state was for.
129129+ */
46130 operation: Ref<Operation<T, V> | undefined>;
131131+ /** Indicates whether {@link useQuery} is currently paused.
132132+ *
133133+ * @remarks
134134+ * When `useQuery` has been paused, it will stop receiving updates
135135+ * from the {@link Client} and won’t execute query operations, until
136136+ * {@link UseQueryArgs.pause} becomes `true` or {@link UseQueryState.resume}
137137+ * is called.
138138+ *
139139+ * @see {@link https://urql.dev/goto/docs/basics/vue#pausing-usequery} for
140140+ * documentation on the `pause` option.
141141+ */
47142 isPaused: Ref<boolean>;
143143+ /** Resumes {@link useQuery} if it’s currently paused.
144144+ *
145145+ * @remarks
146146+ * Resumes or starts {@link useQuery}’s query, if it’s currently paused.
147147+ *
148148+ * @see {@link https://urql.dev/goto/docs/basics/vue#pausing-usequery} for
149149+ * documentation on the `pause` option.
150150+ */
48151 resume(): void;
152152+ /** Pauses {@link useQuery} to stop it from executing the query.
153153+ *
154154+ * @remarks
155155+ * Pauses {@link useQuery}’s query, which stops it from receiving updates
156156+ * from the {@link Client} and to stop the ongoing query operation.
157157+ *
158158+ * @see {@link https://urql.dev/goto/docs/basics/vue#pausing-usequery} for
159159+ * documentation on the `pause` option.
160160+ */
49161 pause(): void;
162162+ /** Triggers {@link useQuery} to execute a new GraphQL query operation.
163163+ *
164164+ * @param opts - optionally, context options that will be merged with
165165+ * {@link UseQueryArgs.context} and the `Client`’s options.
166166+ *
167167+ * @remarks
168168+ * When called, {@link useQuery} will re-execute the GraphQL query operation
169169+ * it currently holds, unless it’s currently paused.
170170+ *
171171+ * This is useful for re-executing a query and get a new network result,
172172+ * by passing a new request policy.
173173+ *
174174+ * ```ts
175175+ * const result = useQuery({ query });
176176+ *
177177+ * const refresh = () => {
178178+ * // Re-execute the query with a network-only policy, skipping the cache
179179+ * result.executeQuery({ requestPolicy: 'network-only' });
180180+ * };
181181+ * ```
182182+ */
50183 executeQuery(opts?: Partial<OperationContext>): UseQueryResponse<T, V>;
51184}
52185186186+/** Return value of {@link useQuery}, which is an awaitable {@link UseQueryState}.
187187+ *
188188+ * @remarks
189189+ * {@link useQuery} returns a {@link UseQueryState} but may also be
190190+ * awaited inside a Vue `async setup()` function. If it’s awaited
191191+ * the query is executed before resolving.
192192+ */
53193export type UseQueryResponse<
54194 T,
55195 V extends AnyVariables = AnyVariables
···59199 flush: 'pre' as const,
60200};
61201202202+/** Function to run a GraphQL query and get reactive GraphQL results.
203203+ *
204204+ * @param args - a {@link UseQueryArgs} object, to pass a `query`, `variables`, and options.
205205+ * @returns a {@link UseQueryResponse} object.
206206+ *
207207+ * @remarks
208208+ * `useQuery` allows GraphQL queries to be defined and executed inside
209209+ * Vue `setup` functions.
210210+ * Given {@link UseQueryArgs.query}, it executes the GraphQL query with the
211211+ * provided {@link Client}.
212212+ *
213213+ * The returned result’s reactive values update when the `Client` has
214214+ * new results for the query, and changes when your input `args` change.
215215+ *
216216+ * Additionally, `useQuery` may also be awaited inside an `async setup()`
217217+ * function to use Vue’s Suspense feature.
218218+ *
219219+ * @see {@link https://urql.dev/goto/docs/basics/vue#queries} for `useQuery` docs.
220220+ *
221221+ * @example
222222+ * ```ts
223223+ * import { gql, useQuery } from '@urql/vue';
224224+ *
225225+ * const TodosQuery = gql`
226226+ * query { todos { id, title } }
227227+ * `;
228228+ *
229229+ * export default {
230230+ * setup() {
231231+ * const result = useQuery({ query: TodosQuery });
232232+ * return { data: result.data };
233233+ * },
234234+ * };
235235+ * ```
236236+ */
62237export function useQuery<T = any, V extends AnyVariables = AnyVariables>(
63238 args: UseQueryArgs<T, V>
64239): UseQueryResponse<T, V> {
+174-11
packages/vue-urql/src/useSubscription.ts
···2222type MaybeRef<T> = Exclude<T, void> | Ref<Exclude<T, void>>;
2323type MaybeRefObj<T extends {}> = { [K in keyof T]: MaybeRef<T[K]> };
24242525+/** Input arguments for the {@link useSubscription} function.
2626+ *
2727+ * @param query - The GraphQL subscription document that `useSubscription` executes.
2828+ * @param variables - The variables for the GraphQL subscription that `useSubscription` executes.
2929+ */
2530export type UseSubscriptionArgs<
2631 Data = any,
2732 Variables extends AnyVariables = AnyVariables
2833> = {
3434+ /** Prevents {@link useSubscription} from automatically executing GraphQL subscription operations.
3535+ *
3636+ * @remarks
3737+ * `pause` may be set to `true` to stop {@link useSubscription} from starting
3838+ * its subscription automatically. This will pause the subscription until
3939+ * {@link UseSubscriptonState.resume} is called, or, if `pause` is a reactive
4040+ * ref of a boolean, until this ref changes to `true`.
4141+ */
2942 pause?: MaybeRef<boolean>;
4343+ /** Updates the {@link OperationContext} for the executed GraphQL subscription operation.
4444+ *
4545+ * @remarks
4646+ * `context` may be passed to {@link useSubscription}, to update the {@link OperationContext}
4747+ * of a subscription operation. This may be used to update the `context` that exchanges
4848+ * will receive for a single hook.
4949+ *
5050+ * @example
5151+ * ```ts
5252+ * const result = useQuery({
5353+ * query,
5454+ * context: {
5555+ * additionalTypenames: ['Item'],
5656+ * },
5757+ * });
5858+ * ```
5959+ */
3060 context?: MaybeRef<Partial<OperationContext>>;
3161} & MaybeRefObj<GraphQLRequestParams<Data, Variables>>;
32626363+/** Combines previous data with an incoming subscription result’s data.
6464+ *
6565+ * @remarks
6666+ * A `SubscriptionHandler` may be passed to {@link useSubscription} to
6767+ * aggregate subscription results into a combined {@link UseSubscriptionResponse.data}
6868+ * value.
6969+ *
7070+ * This is useful when a subscription event delivers a single item, while
7171+ * you’d like to display a list of events.
7272+ *
7373+ * @example
7474+ * ```ts
7575+ * const NotificationsSubscription = gql`
7676+ * subscription { newNotification { id, text } }
7777+ * `;
7878+ *
7979+ * const combineNotifications = (notifications = [], data) => {
8080+ * return [...notifications, data.newNotification];
8181+ * };
8282+ *
8383+ * const result = useSubscription(
8484+ * { query: NotificationsSubscription },
8585+ * combineNotifications,
8686+ * );
8787+ * ```
8888+ */
3389export type SubscriptionHandler<T, R> = (prev: R | undefined, data: T) => R;
9090+9191+/** A {@link SubscriptionHandler} or a reactive ref of one. */
3492export type SubscriptionHandlerArg<T, R> = MaybeRef<SubscriptionHandler<T, R>>;
35933636-export interface UseSubscriptionState<
9494+/** State of the current query, your {@link useSubscription} function is executing.
9595+ *
9696+ * @remarks
9797+ * `UseSubscriptionResponse` is returned by {@link useSubscription} and
9898+ * gives you the updating {@link OperationResult} of GraphQL subscriptions.
9999+ *
100100+ * Each value that is part of the result is wrapped in a reactive ref
101101+ * and updates as results come in.
102102+ *
103103+ * Hint: Even when the query and variables update, the prior state of
104104+ * the last result is preserved.
105105+ */
106106+export interface UseSubscriptionResponse<
37107 T = any,
38108 R = T,
39109 V extends AnyVariables = AnyVariables
40110> {
111111+ /** Indicates whether `useSubscription`’s subscription is active.
112112+ *
113113+ * @remarks
114114+ * When `useSubscription` starts a subscription, the `fetching` flag
115115+ * is set to `true` and will remain `true` until the subscription
116116+ * completes on the API, or `useSubscription` is paused.
117117+ */
41118 fetching: Ref<boolean>;
119119+ /** Indicates that the subscription result is not fresh.
120120+ *
121121+ * @remarks
122122+ * This is mostly unused for subscriptions and will rarely affect you, and
123123+ * is more relevant for queries.
124124+ *
125125+ * @see {@link OperationResult.stale} for the source of this value.
126126+ */
42127 stale: Ref<boolean>;
128128+ /** Reactive {@link OperationResult.data} for the executed subscription, or data returned by the handler.
129129+ *
130130+ * @remarks
131131+ * `data` will be set to the last {@link OperationResult.data} value
132132+ * received for the subscription.
133133+ *
134134+ * It will instead be set to the values that {@link SubscriptionHandler}
135135+ * returned, if a handler has been passed to {@link useSubscription}.
136136+ */
43137 data: Ref<R | undefined>;
138138+ /** Reactive {@link OperationResult.error} for the executed subscription. */
44139 error: Ref<CombinedError | undefined>;
140140+ /** Reactive {@link OperationResult.extensions} for the executed mutation. */
45141 extensions: Ref<Record<string, any> | undefined>;
142142+ /** Reactive {@link Operation} that the current state is for.
143143+ *
144144+ * @remarks
145145+ * This is the subscription {@link Operation} that is currently active.
146146+ * When {@link UseQueryState.fetching} is `true`, this is the
147147+ * last `Operation` that the current state was for.
148148+ */
46149 operation: Ref<Operation<T, V> | undefined>;
150150+ /** Indicates whether {@link useSubscription} is currently paused.
151151+ *
152152+ * @remarks
153153+ * When `useSubscription` has been paused, it will stop receiving updates
154154+ * from the {@link Client} and won’t execute the subscription, until
155155+ * {@link UseSubscriptionArgs.pause} becomes true or
156156+ * {@link UseSubscriptionResponse.resume} is called.
157157+ */
47158 isPaused: Ref<boolean>;
159159+ /** Resumes {@link useSubscription} if it’s currently paused.
160160+ *
161161+ * @remarks
162162+ * Resumes or starts {@link useSubscription}’s subscription, if it’s currently paused.
163163+ */
48164 resume(): void;
165165+ /** Pauses {@link useSubscription} to stop the subscription.
166166+ *
167167+ * @remarks
168168+ * Pauses {@link useSubscription}’s subscription, which stops it
169169+ * from receiving updates from the {@link Client} and to stop executing
170170+ * the subscription operation.
171171+ */
49172 pause(): void;
173173+ /** Triggers {@link useQuery} to reexecute a GraphQL subscription operation.
174174+ *
175175+ * @param opts - optionally, context options that will be merged with
176176+ * {@link UseQueryArgs.context} and the `Client`’s options.
177177+ *
178178+ * @remarks
179179+ * When called, {@link useSubscription} will re-execute the GraphQL subscription
180180+ * operation it currently holds, unless it’s currently paused.
181181+ */
50182 executeSubscription(opts?: Partial<OperationContext>): void;
51183}
521845353-export type UseSubscriptionResponse<
5454- T = any,
5555- R = T,
5656- V extends AnyVariables = AnyVariables
5757-> = UseSubscriptionState<T, R, V>;
5858-59185const watchOptions = {
60186 flush: 'pre' as const,
61187};
62188189189+/** Function to run a GraphQL subscription and get reactive GraphQL results.
190190+ *
191191+ * @param args - a {@link UseSubscriptionArgs} object, to pass a `query`, `variables`, and options.
192192+ * @param handler - optionally, a {@link SubscriptionHandler} function to combine multiple subscription results.
193193+ * @returns a {@link UseSubscriptionResponse} object.
194194+ *
195195+ * @remarks
196196+ * `useSubscription` allows GraphQL subscriptions to be defined and executed inside
197197+ * Vue `setup` functions.
198198+ * Given {@link UseSubscriptionArgs.query}, it executes the GraphQL subscription with the
199199+ * provided {@link Client}.
200200+ *
201201+ * The returned result updates when the `Client` has new results
202202+ * for the subscription, and `data` is updated with the result’s data
203203+ * or with the `data` that a `handler` returns.
204204+ *
205205+ * @example
206206+ * ```ts
207207+ * import { gql, useSubscription } from '@urql/vue';
208208+ *
209209+ * const NotificationsSubscription = gql`
210210+ * subscription { newNotification { id, text } }
211211+ * `;
212212+ *
213213+ * export default {
214214+ * setup() {
215215+ * const result = useSubscription(
216216+ * { query: NotificationsSubscription },
217217+ * function combineNotifications(notifications = [], data) {
218218+ * return [...notifications, data.newNotification];
219219+ * },
220220+ * );
221221+ * // ...
222222+ * },
223223+ * };
224224+ * ```
225225+ */
63226export function useSubscription<
64227 T = any,
65228 R = T,
66229 V extends AnyVariables = AnyVariables
67230>(
68231 args: UseSubscriptionArgs<T, V>,
6969- handler?: SubscriptionHandlerArg<T, R>
232232+ handler?: MaybeRef<SubscriptionHandler<T, R>>
70233): UseSubscriptionResponse<T, R, V> {
71234 return callUseSubscription(args, handler);
72235}
···77240 V extends AnyVariables = AnyVariables
78241>(
79242 _args: UseSubscriptionArgs<T, V>,
8080- handler?: SubscriptionHandlerArg<T, R>,
243243+ handler?: MaybeRef<SubscriptionHandler<T, R>>,
81244 client: Ref<Client> = useClient(),
82245 stops: WatchStopHandle[] = []
83246): UseSubscriptionResponse<T, R, V> {
···159322 }, watchOptions)
160323 );
161324162162- const state: UseSubscriptionState<T, R, V> = {
325325+ const state: UseSubscriptionResponse<T, R, V> = {
163326 data,
164327 stale,
165328 error,
···169332 isPaused,
170333 executeSubscription(
171334 opts?: Partial<OperationContext>
172172- ): UseSubscriptionState<T, R, V> {
335335+ ): UseSubscriptionResponse<T, R, V> {
173336 source.value = client.value.executeSubscription<T, V>(request.value, {
174337 ...unwrapPossibleProxy(args.context),
175338 ...opts,