### Install relay-hooks and react-relay Packages Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/RelayHooks-Introduction.md Instructions to add the necessary `react-relay` and `relay-hooks` packages to your project using either Yarn or npm package managers. ```Shell yarn add react-relay relay-hooks ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/todo/README.md Installs all required Node.js packages and project dependencies using Yarn. This command should be run once after cloning the repository. ```bash yarn ``` -------------------------------- ### Start Local Development Server Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/todo/README.md Launches the local development server for the Relay Hooks TodoMVC application. This command allows you to access and interact with the application in your browser. ```bash yarn run start ``` -------------------------------- ### Basic useQuery Hook Implementation Example Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/RelayHooks-Introduction.md An example demonstrating the fundamental usage of the `useQuery` hook from `relay-hooks`. It shows how to define a GraphQL query, set variables and options, and integrate the hook within a React functional component to display data, handle errors, or indicate loading states. ```TypeScript import { useQuery, graphql } from 'relay-hooks'; const query = graphql` query appQuery($userId: String) { user(id: $userId) { ...TodoApp_user } } `; const variables = { userId: 'me', }; const options = { fetchPolicy: 'store-or-network', //default networkCacheConfig: undefined, } const AppTodo = function (appProps) { const { data, error, retry, isLoading } = useQuery(query, variables, options); if (data && data.user) { return ; } else if (error) { return
{error.message}
; } return
loading
; } ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/pagination-nextjs-ssr/README.md Installs all required project dependencies using the Yarn package manager. This step is crucial before running any other commands. ```shell yarn ``` -------------------------------- ### useQuery Hook Options Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/RelayHooks-Introduction.md Detailed reference for the `options` argument accepted by the `useQuery` hook, outlining available properties like `fetchPolicy`, `fetchKey`, `networkCacheConfig`, `skip`, and `onComplete`, along with their descriptions and possible values. ```APIDOC useQuery(query, variables, options): options: Object fetchPolicy: string (default: 'store-or-network') Description: Determines data caching and network request behavior. Values: - 'store-or-network': Reuse cached data; skip network if whole query is cached. - 'store-and-network': Reuse cached data; always send network request. - 'network-only': Don't reuse cached data; always send network request. - 'store-only': Reuse cached data; never send network request. fetchKey: any (Optional) Description: Forces a refetch of the current query and variables if its value changes on re-render. networkCacheConfig: Object (Optional) Description: Configuration options for the network layer's cache. Pass {force: true} to bypass completely. skip: boolean (Optional) Description: If true, the query will be entirely skipped. onComplete: Function (Optional) Description: Callback function executed when the fetch request has completed. ``` -------------------------------- ### Generate Schema and Build Project Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/todo/README.md Sets up generated files by updating the GraphQL schema and building the project. This is a prerequisite for running the application and should be executed after installation or schema changes. ```bash yarn run update-schema yarn run build ``` -------------------------------- ### Set Up Generated Files Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr/README.md Prepares the project by running initial setup commands, including installing dependencies and compiling necessary files. This step is crucial for ensuring all generated code is in place before development. ```bash yarn yarn compile ``` -------------------------------- ### relay-hooks API Differences and Extensions Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/RelayHooks-Introduction.md This section outlines the key differences and additional features provided by `relay-hooks` compared to the official `react-relay` hooks, including custom hook names and extended parameters for existing functionalities. ```APIDOC useLazyLoadQuery (relay-hooks vs. official): - Returns: single data object with the query's data. useSuspenseFragment (relay-hooks): - Equivalent to official useFragment. useQuery (relay-hooks): - Description: Similar to useLazyLoadQuery but does not use suspense; return matches QueryRenderer HOC. - Parameters: - skip: boolean (Optional) - If true, the query will be skipped entirely. - onComplete: function (Optional) - Function called whenever the fetch request has completed. - fetchObserver: object (Optional) - A fetchObserver can be passed to observe the execution of the query in the network. useRefetch (relay-hooks): - Description: Equivalent to official useRefetchable; allows migrating Refetch Container without changing fragment specifications. ``` -------------------------------- ### useLazyLoadQuery with Suspense and Error Boundary Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/RelayHooks-Introduction.md An advanced example showcasing the `useLazyLoadQuery` hook integrated with React's Suspense and Error Boundary features. This snippet demonstrates how to set up a robust data fetching environment using `RelayEnvironmentProvider` for a complete Relay application. ```TypeScript import * as React from 'react'; import { useQuery, graphql, RelayEnvironmentProvider } from 'relay-hooks'; const query = graphql` query appQuery($userId: String) { user(id: $userId) { ...TodoApp_user } } `; class ErrorBoundary extends React.Component { state = { error: null }; componentDidCatch(error) { this.setState({ error }); } render() { const { children, fallback } = this.props; const { error } = this.state; if (error) { return React.createElement(fallback, { error }); } return children; } } const variables = { userId: 'me', }; const options = { fetchPolicy: 'store-or-network', //default networkCacheConfig: undefined, } const AppTodo = function (appProps) { const { data } = useLazyLoadQuery(query, variables, options); return ; } const App = ( `Error: ${error.message + ': ' + error.stack}`}> loading suspense}> ); ``` -------------------------------- ### Configure RelayEnvironmentProvider for React Application Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/RelayHooks-Introduction.md Demonstrates how to wrap your root React application component with `RelayEnvironmentProvider`. This component takes a Relay `environment` instance and makes it available to all child components that utilize `relay-hooks`, ensuring proper context for queries and fragments. ```TypeScript import { RelayEnvironmentProvider } from 'relay-hooks'; ReactDOM.render( , rootElement, ); ``` -------------------------------- ### Start Local Development Server Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/pagination-nextjs-ssr/README.md Initiates the local development server for the Next.js application. This command typically watches for file changes and provides hot-reloading capabilities for development. ```shell yarn dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/nextjs-ssr-preload/README.md Installs all necessary project dependencies using Yarn. ```bash yarn ``` -------------------------------- ### Set Up Generated Files Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/nextjs-ssr-preload/README.md Prepares the project by installing dependencies and compiling any necessary generated files, such as GraphQL artifacts or TypeScript output. ```bash yarn yarn compile ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr-preload/README.md Installs all required Node.js packages and dependencies for the project using Yarn. ```shell yarn ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr/README.md Installs all necessary project dependencies using Yarn. This should be the first step after cloning the repository. ```bash yarn ``` -------------------------------- ### Run Relay Hooks TodoMVC Application Locally Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/cra/README.md These commands sequentially compile the Relay Hooks TodoMVC project, start the development server, and then launch the application. This sequence is crucial for local development and testing the application's functionality. ```shell yarn compile yarn server yarn start ``` -------------------------------- ### Install Project Dependencies for Relay Hooks TodoMVC Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/cra/README.md This command installs all required project dependencies using Yarn. It ensures that all necessary packages are available for compiling and running the application. ```shell yarn ``` -------------------------------- ### Example of Preloading Data with Relay Hooks loadQuery Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePreloadedQuery.md This TypeScript example demonstrates how to use `loadQuery` to prefetch GraphQL data. It defines a GraphQL query, initializes `loadQuery`, and then executes the query with specific variables and fetch policy, preparing the data for `usePreloadedQuery`. ```typescript import {graphql, loadQuery} from 'relay-hooks'; import {environment} from ''./environment'; const query = graphql` query AppQuery($id: ID!) { user(id: $id) { name } } `; const prefetch = loadQuery(); prefetch.next( environment, query, {id: '4'}, {fetchPolicy: 'store-or-network'}, ); // pass prefetch to usePreloadedQuery() ``` -------------------------------- ### Rebuild and Restart Development Environment After Schema Changes Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/todo/README.md Provides the complete sequence of commands to regenerate the GraphQL schema, rebuild the project, and restart the development server. This is necessary when changes are made to 'data/schema.js'. ```bash yarn run update-schema yarn run build yarn run start ``` -------------------------------- ### Compile Generated Files Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/pagination-nextjs-ssr/README.md Executes the necessary steps to set up and compile generated files, which are often required for Relay or GraphQL projects. This ensures that all schema and type definitions are up-to-date. ```shell yarn yarn compile ``` -------------------------------- ### Start Local Development Server Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/nextjs-ssr-preload/README.md Initiates the local development server for the Next.js application, allowing the project to be accessed in a web browser. ```bash yarn dev ``` -------------------------------- ### Start Local Development Server Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr-preload/README.md Initiates the Next.js development server, allowing the application to be accessed locally for development and testing purposes. ```shell yarn dev ``` -------------------------------- ### Example Usage of useRefetchable Hook in React Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useRefetchable.md This TypeScript example demonstrates how to integrate the `useRefetchable` hook into a React component. It shows the definition of a GraphQL fragment using `@refetchable`, how to destructure `data` and `refetch` from the hook, and how to trigger a refetch operation via a button click. ```typescript import { useRefetchable, graphql } from 'relay-hooks'; const fragmentSpec = graphql` fragment TodoList_user on User @refetchable(queryName: "TodoListRefetchQuery") { todos( first: 2147483647 # max GraphQLInt ) @connection(key: "TodoList_todos") { edges { node { id complete ...Todo_todo } } } id userId totalCount completedCount ...Todo_user } `; const options = { renderVariables: null, observerOrCallback: () => { console.log('Refetch done') }, refetchOptions: {force: true}, } const TodoApp = (props) => { const { data: user, refetch } = useRefetchable(fragmentSpec, props.user); const handlerRefetch = React.useCallback( () => refetch({}), [refetch]); return (

{user.id}

{user.userId}

{user.totalCount}

); }; ``` -------------------------------- ### Install relay-hooks and react-relay Source: https://github.com/relay-tools/relay-hooks/blob/master/README.md Instructions to install the `react-relay` and `relay-hooks` packages using Yarn, which are necessary dependencies for using Relay with React hooks. ```bash yarn add react-relay relay-hooks ``` -------------------------------- ### Example of Consuming Preloaded Data with usePreloadedQuery Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePreloadedQuery.md This TypeScript example shows a simple React component using the `usePreloadedQuery` hook. It takes the preloaded data (e.g., from `loadQuery`) as a prop and makes it accessible within the component, demonstrating how to render data fetched server-side or preloaded client-side. ```typescript function Component(props) { data = usePreloadedQuery(props.prefetched); return data; } ``` -------------------------------- ### Start Local Development Server Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr/README.md Launches the Next.js development server for the project. This allows you to access the application locally in your browser and enables hot-reloading for development. ```bash yarn dev ``` -------------------------------- ### Example Usage of Relay useQuery Hook Source: https://github.com/relay-tools/relay-hooks/blob/master/README.md Demonstrates how to use the `useQuery` hook with `graphql` and `relay-hooks` to fetch user data, handle loading states, and display errors in a React component. ```TypeScript import { useQuery, graphql } from 'relay-hooks'; const query = graphql` query appQuery($userId: String) { user(id: $userId) { ...TodoApp_user } } `; const variables = { userId: 'me', }; const options = { fetchPolicy: 'store-or-network', //default networkCacheConfig: undefined, } const AppTodo = function (appProps) { const {data, error, retry, isLoading} = useQuery(query, variables, options); if (data && data.user) { return ; } else if (error) { return
{error.message}
; } return
loading
; } ``` -------------------------------- ### Differentiate Relay Query Loading (Suspense vs. No Suspense) Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr-preload/README.md Illustrates the distinct approaches to prefetching queries in Relay Hooks based on whether Suspense is utilized. `loadLazyQuery` is used for Suspense-enabled environments, while `loadQuery` is for non-Suspense setups. ```typescript // suspense import {loadLazyQuery} from 'relay-hooks'; const prefetch = loadLazyQuery(); // no suspense import {loadQuery} from 'relay-hooks'; const prefetch = loadQuery(); ``` -------------------------------- ### Example Usage of Relay useLazyLoadQuery Hook Source: https://github.com/relay-tools/relay-hooks/blob/master/README.md Illustrates the usage of `useLazyLoadQuery` within a React component, including error boundary and suspense integration for asynchronous data loading with Relay. ```TypeScript import * as React from 'react'; import { useQuery, graphql, RelayEnvironmentProvider } from 'relay-hooks'; const query = graphql` query appQuery($userId: String) { user(id: $userId) { ...TodoApp_user } } `; class ErrorBoundary extends React.Component { state = { error: null }; componentDidCatch(error) { this.setState({ error }); } render() { const { children, fallback } = this.props; const { error } = this.state; if (error) { return React.createElement(fallback, { error }); } return children; } } const variables = { userId: 'me', }; const options = { fetchPolicy: 'store-or-network', //default networkCacheConfig: undefined, } const AppTodo = function (appProps) { const {data} = useLazyLoadQuery(query, variables, options); return ; } const App = ( `Error: ${error.message + ': ' + error.stack}`}> loading suspense}> ); ``` -------------------------------- ### Implement Pagination with usePagination Hook in Relay Hooks Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePagination.md Demonstrates how to use the `usePagination` hook in Relay Hooks to implement client-side pagination. It defines a GraphQL fragment with `@refetchable` and `@connection` directives, then uses `usePagination` to manage data loading, `isLoadingNext`, `hasNext`, and `loadNext` for paginating a list of items. The example includes a 'Load More' button to trigger additional data fetches. ```typescript import { usePagination, graphql } from 'relay-hooks'; const fragmentSpec = graphql` fragment Feed_user on User @argumentDefinitions( count: {type: "Int", defaultValue: 10} cursor: {type: "ID"} orderby: {type: "[FriendsOrdering]", defaultValue: [DATE_ADDED]} ) @refetchable(queryName: "FeedRefetchQuery") { feed( first: $count after: $cursor orderby: $orderBy # Non-pagination variables ) @connection(key: "Feed_feed") { edges { node { id ...Story_story } } } } `; const Feed = (props) => { const { data: user, isLoadingNext, hasNext, loadNext } = usePagination(fragmentSpec, props.user); const _loadMore = () => { if (!hasMore || isLoading) { return; } const onComplete = (error: Error | null) => { console.log("Complete", error); } loadMore(10, { onComplete }); } return (
{user.feed.edges.map( edge => )}
); }; ``` -------------------------------- ### Example React Component using useMutation Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useMutation.md This snippet demonstrates how to integrate the `useMutation` hook into a React functional component. It shows defining a GraphQL mutation, handling the `onCompleted` callback, and triggering the mutation via a button click, along with displaying a loading indicator. ```js import React from 'react'; import { useMutation } from 'relay-hooks'; /* ... */ function MyComponentWithHook({ myValue }) { const [mutate, { loading }] = useMutation( graphql` mutation ExampleWithHookMutation($input: MyMutationInput) { myMutation(input: $input) { value } } `, { onCompleted: ({ myMutation }) => { window.alert(`received ${myMutation.value}`); }, }, ); return loading ? ( ) : ( ); } ``` -------------------------------- ### Implement Callback-based Data Updates with useFragmentSubscription in TypeScript Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useFragment.md This TypeScript example illustrates the usage of `useFragmentSubscription`, an alternative to `useFragment` that provides data updates via a callback. This approach is beneficial for components where frequent re-renders are expensive, allowing for more controlled updates based on the latest fragment data. ```TypeScript import * as React from 'react'; import { useFragmentSubscription, graphql } from 'relay-hooks'; const fragmentSpec = graphql` fragment TodoApp_user on User { id userId totalCount } `; const TodoApp = (props) => { const ref = React.useRef() useFragmentSubscription( fragmentSpec, props.user, React.useCallback((user) => { ref.current.updateUserInformation(user); }, []) ); return ( ); }; ``` -------------------------------- ### Implement Data Requirements with useFragment in TypeScript Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useFragment.md This TypeScript example demonstrates how to use the `useFragment` hook from `relay-hooks` to declare a component's data requirements using a GraphQL fragment. The component automatically re-renders when the associated fragment data is updated in the Relay store, ensuring the UI reflects the latest state. ```TypeScript import { useFragment, graphql } from 'relay-hooks'; const fragmentSpec = graphql` fragment TodoApp_user on User { id userId totalCount } `; const TodoApp = (props) => { const user = useFragment(fragmentSpec, props.user); return (

{user.id}

{user.userId}

{user.totalCount}

); }; ``` -------------------------------- ### useRefetchable Hook API Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useRefetchable.md Detailed API documentation for the `useRefetchable` hook, outlining its arguments, the properties of its return value, and the specific behavior of the `refetch` function, including its parameters and return type. ```APIDOC useRefetchable(fragmentSpec, initialData): Arguments: - Same as useFragment (refer to useFragment documentation) Return Value: Object - data: Object - Description: Object that contains data which has been read out from the Relay store; the object matches the shape of specified fragment. - error: Error - Description: Error will be defined if an error has occurred while refetching the query. - isLoading: Boolean - Description: Boolean value which indicates if a refetch is currently in flight, including any incremental data payloads. - refetch(variables: Object, options: Object): Disposable - Description: Function used to refetch the connection fragment with a potentially new set of variables. - Arguments: - variables: Object - Description: Object containing the new set of variable values to be used to fetch the `@refetchable` query. - Notes: - These variables need to match GraphQL variables referenced inside the fragment. - Only the variables that are intended to change for the refetch request need to be specified; any variables referenced by the fragment that are omitted from this input will fall back to using the value specified in the original parent query. So for example, to refetch the fragment with the exact same variables as it was originally fetched, you can call `refetch({})`. - Similarly, passing an `id` value for the `$id` variable is _*optional*_, unless the fragment wants to be refetched with a different `id`. When refetching a `@refetchable` fragment, Relay will already know the id of the rendered object. - options: Object (Optional) - fetchPolicy: String - Description: Determines if cached data should be used, and when to send a network request based on cached data that is available. See the `useQuery` section for full specification. - onComplete: Function - Description: Function that will be called whenever the refetch request has completed, including any incremental data payloads. - Return Value: Disposable - disposable: Object - dispose(): Function - Description: Calling `disposable.dispose()` will cancel the refetch request. - Behavior: - Calling `refetch` with a new set of variables will fetch the fragment again ***with the newly provided variables***. Note that the variables you need to provide are only the ones referenced inside the fragment. - Calling `refetch` ***will not*** cause the component to suspend. Instead, the `isLoading` value will be set to true while the request is in flight. Behavior: - The component is automatically subscribed to updates to the fragment data: if the data for this particular `User` is updated anywhere in the app (e.g. via fetching new data, or mutating existing data), the component will automatically re-render with the latest updated data. ``` -------------------------------- ### Configure Robots.txt to Allow All Web Crawlers Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/relay-hook-example/cra/public/robots.txt This snippet illustrates a basic robots.txt configuration designed to grant full access to all web crawlers. The `User-agent: *` directive specifies that the following rules apply to all robots. An empty `Disallow:` directive means that no paths are restricted, allowing bots to crawl the entire website without limitations. ```Plain Text User-agent: * Disallow: ``` -------------------------------- ### Relay useQuery Hook Options Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/README.md Detailed documentation for the options available when using the `useQuery` hook in Relay, including fetch policies, caching configurations, and lifecycle callbacks. ```APIDOC useQuery(query: GraphQLTaggedNode, variables: object, options?: object): {data: any, error: Error, retry: Function, isLoading: boolean} options: fetchPolicy: string 'store-or-network' (default): Reuse data cached in the store; if the whole query is cached, skip the network request 'store-and-network': Reuse data cached in the store; always send a network request. 'network-only': Don't reuse data cached in the store; always send a network request. 'store-only': Reuse data cached in the store; never send a network request. fetchKey: any (Optional) Description: A fetchKey can be passed to force a refetch of the current query and variables when the component re-renders. networkCacheConfig: object (Optional) Description: Object containing cache config options for the network layer. Pass {force: true} to bypass this cache completely. skip: boolean (Optional) Description: If true, the query will be skipped entirely. onComplete: Function (Optional) Description: Function that will be called whenever the fetch request has completed. ``` -------------------------------- ### Relay Hooks usePreloadedQuery API Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePreloadedQuery.md Outlines the input and output parameters for the `usePreloadedQuery` hook. It consumes the output of `loadQuery` or `loadLazyQuery` and provides the same output as `useQuery`, making preloaded data available to components. ```APIDOC usePreloadedQuery: input parameters: loadQuery | loadLazyQuery output parameters: same as useQuery ``` -------------------------------- ### Generate Relay Artifacts and Compile Project Source: https://github.com/relay-tools/relay-hooks/blob/master/examples/suspense/nextjs-ssr-preload/README.md Sets up necessary generated files for Relay and compiles the TypeScript project. This step is crucial for Relay's static analysis and code generation. ```shell yarn yarn compile ``` -------------------------------- ### Relay Hooks loadQuery API Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePreloadedQuery.md Details the `loadQuery` function's input and output parameters. It's used for fetching data, returning a promise for SSR, and providing methods for disposal, subscription, and value retrieval. ```APIDOC loadQuery: input parameters: same as useQuery + environment output parameters: next: signature: (environment: IEnvironment, gqlQuery: GraphQLTaggedNode, variables?: TOperationType['variables'], options?: QueryOptions) => Promise description: fetches data. A promise returns to allow the await in case of SSR dispose: signature: () => void description: cancel the subscription and dispose of the fetch subscribe: signature: (callback: (value: any) => any) => () => void description: used by the usePreloadedQuery getValue: signature: (environment?: IEnvironment) => RenderProps | Promise description: used by the usePreloadedQuery ``` -------------------------------- ### Import useSuspenseFragment for Suspense-enabled Data Fetching Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useFragment.md This snippet shows the basic import for `useSuspenseFragment`, a hook designed for suspense-enabled data fetching in Relay, similar to `relay-experimental` patterns. It allows components to suspend rendering until data is available. ```TypeScript import { useSuspenseFragment } from 'relay-hooks'; ``` -------------------------------- ### relay-hooks API Differences and Extensions Source: https://github.com/relay-tools/relay-hooks/blob/master/README.md Details the key differences between `relay-hooks` and the upcoming official Relay Hooks, along with additional features and parameters provided by `relay-hooks` for its `useQuery` and `useLazyLoadQuery` hooks. ```APIDOC useLazyLoadQuery: - Returns: A single data object with the query's data. useFragment: - In relay-hooks: useSuspenseFragment useQuery: - Description: Same as useLazyLoadQuery but does not use suspense. - Returns: Same as the QueryRenderer HOC. Conditional useQuery & useLazyLoadQuery: - Parameters: - skip: - Type: boolean - Description: If true, the query will be skipped entirely. - Optional: Yes Observe execution of query in network (useQuery & useLazyLoadQuery): - Parameters: - onComplete: - Type: Function - Description: Called whenever the fetch request has completed. - Optional: Yes RelayEnvironmentProvider: - Type: React Component - Props: - environment: - Type: Relay.Environment - Description: The Relay environment to be set in context for child components. - Usage: Should be rendered once at the root of the app. ``` -------------------------------- ### Relay Hooks usePagination API Reference and Behavior Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePagination.md Comprehensive documentation for the `usePagination` hook, detailing its parameters (`fetchPolicy`, `onComplete`), return values (`disposable`), and core behaviors. It also highlights key differences and improvements compared to the older `PaginationContainer` API, such as automatic subscription, bi-directional pagination support, and simplified variable handling for refetching. ```APIDOC * `fetchPolicy`: Determines if cached data should be used, and when to send a network request based on cached data that is available. See the [`useQuery`](https://relay-tools.github.io/relay-hooks/docs/relay-hooks#usequery) section for full specification. * `onComplete`: Function that will be called whenever the refetch request has completed, including any incremental data payloads. * Return value: * `disposable`: Object containing a `dispose` function. Calling `disposable.dispose()` will cancel the refetch request. * Behavior: * Calling `refetch` with a new set of variables will fetch the fragment again ***with the newly provided variables***. Note that the variables you need to provide are only the ones referenced inside the fragment. * Calling `refetch` ***will not*** cause the component to suspend. Instead, the `isLoading` value will be set to true while the request is in flight ## Behavior * The component is automatically subscribed to updates to the fragment data: if the data for this particular `User` is updated anywhere in the app (e.g. via fetching new data, or mutating existing data), the component will automatically re-render with the latest updated data. ## Differences with `PaginationContainer` * A pagination query no longer needs to be specified in this api, since it will be automatically generated by Relay by using a `@refetchable` fragment. * This api supports simultaneous bi-directional pagination out of the box. * This api no longer requires passing a `getVariables` or `getFragmentVariables` configuration functions, like the `PaginationContainer` does. * This implies that pagination no longer has a between `variables` and `fragmentVariables`, which were previously vaguely defined concepts. Pagination requests will always use the same variables that were originally used to fetch the connection, *except* pagination variables (which need to change in order to perform pagination); changing variables other than the pagination variables during pagination doesn't make sense, since that'd mean we'd be querying for a different connection. * This api no longer takes additional configuration like `direction` or `getConnectionFromProps` function (like Pagination Container does). These values will be automatically determined by Relay. * Refetching no longer has a distinction between `variables` and `fragmentVariables`, which were previously vaguely defined concepts. Refetching will always correctly refetch and render the fragment with the variables you provide (any variables omitted in the input will fallback to using the original values in the parent query). * Refetching will unequivocally update the component, which was not always true when calling `refetchConnection` from `PaginationContainer` (it would depend on what you were querying for in the refetch query and if your fragment was defined on the right object type). ``` -------------------------------- ### API Specification for useFragment Hook Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useFragment.md This section details the arguments and return value for the `useFragment` hook. It explains the purpose of the `fragment` and `fragmentReference` arguments, including type information for the latter, and describes the structure of the `data` object returned. ```APIDOC useFragment: Arguments: fragment: GraphQL fragment specified using a graphql template literal. fragmentReference: The fragment reference is an opaque Relay object that Relay uses to read the data for the fragment from the store; more specifically, it contains information about which particular object instance the data should be read from. The type of the fragment reference can be imported from the generated Flow types, from the file .graphql.js, and can be used to declare the type of your Props. The name of the fragment reference type will be: $key. We use our [lint rule](https://github.com/relayjs/eslint-plugin-relay) to enforce that the type of the fragment reference prop is correctly declared. Return Value: data: Object that contains data which has been read out from the Relay store; the object matches the shape of specified fragment. ``` -------------------------------- ### Import usePaginationFragment Hook from Relay Hooks Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePagination.md Shows the basic import statement for the `usePaginationFragment` hook from the `relay-hooks` library, indicating its availability for use in Relay applications. ```typescript import { usePaginationFragment } from 'relay-hooks'; ``` -------------------------------- ### useMutation Hook API Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useMutation.md Detailed API documentation for the `useMutation` hook. It outlines the hook's parameters, the structure of its return value (the `mutate` callback and `mutationState` object), and the properties available within the `mutationState` for managing mutation lifecycle and data. ```APIDOC useMutation(mutationNode: GraphQLTaggedNode, options?: MutationOptions): mutationNode: A GraphQL mutation node. options: Optional configuration object, valid for `commitMutation` in Relay. onCompleted: Callback for successful mutation, takes response as single argument. onError: Callback for errors (if specified, promise resolves with no value on error). optimisticResponse: An optimistic response for UI updates. Returns: [mutate: Function, mutationState: Object] mutate(options?: Object): Callback to execute the mutation. options: Overrides options passed to `useMutation`. `variables` must be specified here if not in `useMutation` options. Returns: Promise (resolves with response or rejects with error, unless `onError` is specified). mutationState: Object containing mutation status. loading: boolean - True if mutation is pending. data: any - Response data (optimistic when `loading` is true, server response when `loading` is false). error: any - Any errors returned by the mutation. ``` -------------------------------- ### Importing useRefetchableFragment Hook Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useRefetchable.md Illustrates the standard TypeScript import statement for the `useRefetchableFragment` hook, a key component of the `relay-hooks` library used for managing data refetching in Relay applications. ```typescript import { useRefetchableFragment } from 'relay-hooks'; ``` -------------------------------- ### Relay Hook Return Object Properties and Methods Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePagination.md This documentation describes the structure and functionality of the object returned by Relay hooks, specifically focusing on pagination and refetching capabilities. It details properties for data, error states, loading indicators, connection status, and methods for loading next/previous items and refetching the fragment. ```APIDOC ReturnObject: data: Object Description: Object that contains data read from the Relay store, matching the shape of the specified fragment. error: Error Description: Defined if an error occurred while refetching the query. errorNext: Error Description: Defined if an error occurred while fetching the *next* items. errorPrevious: Error Description: Defined if an error occurred while fetching the *previous* items. isLoading: Boolean Description: Indicates if a refetch is currently in flight, including any incremental data payloads. isLoadingNext: Boolean Description: Indicates if a pagination request for the *next* items in the connection is currently in flight. isLoadingPrevious: Boolean Description: Indicates if a pagination request for the *previous* items in the connection is currently in flight. hasNext: Boolean Description: Indicates if the end of the connection has been reached in the “forward” direction. True if more items are available. hasPrevious: Boolean Description: Indicates if the end of the connection has been reached in the “backward” direction. True if more items are available. loadNext(count: Number, options?: Object): disposable Description: Function used to fetch more items in the connection in the “forward” direction. Arguments: count: Number Description: Number that indicates how many items to query for in the pagination request. options: Object (Optional) onComplete: Function Description: Function that will be called whenever the refetch request has completed, including any incremental data payloads. Return Value: disposable: Object Description: Object containing a `dispose` function. Calling `disposable.dispose()` will cancel the pagination request. Behavior: - Calling `loadNext` will not cause the component to suspend. Instead, `isLoadingNext` will be set to true while the request is in flight. - New items from the pagination request will be added to the connection, causing the component to re-render. - Pagination requests initiated from calling `loadNext` will always use the same variables that were originally used to fetch the connection, except pagination variables. loadPrevious(count: Number, options?: Object): disposable Description: Function used to fetch more items in the connection in the “backward” direction. Arguments: count: Number Description: Number that indicates how many items to query for in the pagination request. options: Object (Optional) onComplete: Function Description: Function that will be called whenever the refetch request has completed, including any incremental data payloads. Return Value: disposable: Object Description: Object containing a `dispose` function. Calling `disposable.dispose()` will cancel the pagination request. Behavior: - Calling `loadPrevious` will not cause the component to suspend. Instead, `isLoadingPrevious` will be set to true while the request is in flight. - New items from the pagination request will be added to the connection, causing the component to re-render. - Pagination requests initiated from calling `loadPrevious` will always use the same variables that were originally used to fetch the connection, except pagination variables. refetch(variables: Object, options?: Object): void Description: Function used to refetch the connection fragment with a potentially new set of variables. Arguments: variables: Object Description: Object containing the new set of variable values to be used to fetch the `@refetchable` query. - These variables need to match GraphQL variables referenced inside the fragment. - Only variables intended to change need to be specified; omitted variables fall back to original parent query values. - Example: `refetch({})` refetches with the exact same variables as originally fetched. - Passing an `id` value for the `$id` variable is optional, unless the fragment wants to be refetched with a different `id`. ``` -------------------------------- ### Implementing GraphQL Subscriptions with useSubscription in React Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useSubscription.md This snippet demonstrates how to use the `useSubscription` hook from `relay-hooks` within a React functional component. It defines a GraphQL subscription query and then uses `useSubscription` to initiate and manage the subscription. It also highlights the critical importance of memoizing the subscription configuration object to prevent unnecessary re-subscriptions on every render. ```ts import { useMemo } from 'react'; import { useSubscription, graphql } from 'relay-hooks'; const subscriptionSpec = graphql` subscription TodoSubscription { todos { node { id text complete } } } `; const TodoList = (props) => { // NOTE: This will re-subscribe every render if config is not memoized. Please // do not pass an object defined inline. useSubscription( useMemo(() => ({ subscription: subscriptionSpec, variables: {} }), []) ); // ??? }; ``` -------------------------------- ### Relay Hooks loadLazyQuery API Reference Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/usePreloadedQuery.md Describes `loadLazyQuery` as functionally similar to `loadQuery` but specifically designed for use with React Suspense. It's intended for scenarios where data loading should integrate with Suspense boundaries. ```APIDOC loadLazyQuery: description: is the same as loadQuery but must be used with suspense ``` -------------------------------- ### Configure RelayEnvironmentProvider for React App Source: https://github.com/relay-tools/relay-hooks/blob/master/README.md Demonstrates how to wrap a React application with `RelayEnvironmentProvider`. This component takes a Relay `environment` and sets it in context, making it available for `useQuery` hooks throughout the application's component tree. ```typescript import { RelayEnvironmentProvider } from 'relay-hooks'; ReactDOM.render( , rootElement, ); ``` -------------------------------- ### API Specification for useFragmentSubscription Hook Source: https://github.com/relay-tools/relay-hooks/blob/master/docs/useFragment.md This section outlines the arguments and return value for the `useFragmentSubscription` hook. It describes the `fragment`, `fragmentReference`, and the `onFragmentData` callback, which is invoked with the latest fragment data, noting that the hook itself returns no value. ```APIDOC useFragmentSubscription: Arguments: fragment: GraphQL fragment specified using a graphql template literal. fragmentReference: The fragment reference is an opaque Relay object that Relay uses to read the data for the fragment from the store; more specifically, it contains information about which particular object instance the data should be read from. The type of the fragment reference can be imported from the generated Flow types, from the file .graphql.js, and can be used to declare the type of your Props. The name of the fragment reference type will be: $key. We use our [lint rule](https://github.com/relayjs/eslint-plugin-relay) to enforce that the type of the fragment reference prop is correctly declared. onFragmentData: A callback that will be invoked with the latest fragment data. Return Value: void: This hook returns no value ``` -------------------------------- ### JavaScript Page Redirection Source: https://github.com/relay-tools/relay-hooks/blob/master/website/static/index.html This JavaScript snippet redirects the current browser window to a specified URL. It's commonly used for automatic navigation, often paired with a manual fallback link for users whose browsers might block JavaScript redirects or for accessibility. ```JavaScript window.location.href = 'https://morrys.github.io/website/'; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.