or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-apollo--react-components

React Apollo Query, Mutation and Subscription components for declarative GraphQL operations.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@apollo/react-components@4.0.x

To install, run

npx @tessl/cli install tessl/npm-apollo--react-components@4.0.0

index.mddocs/

Apollo React Components

Apollo React Components provides React component wrappers for Apollo GraphQL client functionality, specifically the Query, Mutation, and Subscription components that enable declarative GraphQL operations in React applications. This package serves as a wrapper that re-exports all functionality from @apollo/client and @apollo/client/react/components.

Important: This package is deprecated as of Apollo Client 3.0. It's recommended to import directly from @apollo/client instead.

Package Information

  • Package Name: @apollo/react-components
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install @apollo/react-components

Core Imports

import { Query, Mutation, Subscription } from "@apollo/react-components";

For CommonJS:

const { Query, Mutation, Subscription } = require("@apollo/react-components");

Import everything (including Apollo Client core):

import { 
  Query, Mutation, Subscription,
  ApolloClient, ApolloProvider, gql, useQuery, useMutation 
} from "@apollo/react-components";

Basic Usage

import { Query, Mutation, Subscription, gql } from "@apollo/react-components";

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

const CREATE_USER = gql`
  mutation CreateUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) {
      id
      name
      email
    }
  }
`;

// Query component usage
function UsersList() {
  return (
    <Query query={GET_USERS}>
      {({ loading, error, data }) => {
        if (loading) return <p>Loading...</p>;
        if (error) return <p>Error: {error.message}</p>;
        
        return (
          <ul>
            {data.users.map(user => (
              <li key={user.id}>{user.name} - {user.email}</li>
            ))}
          </ul>
        );
      }}
    </Query>
  );
}

// Mutation component usage
function CreateUserForm() {
  return (
    <Mutation mutation={CREATE_USER}>
      {(createUser, { loading, error, data }) => (
        <form onSubmit={e => {
          e.preventDefault();
          const formData = new FormData(e.target);
          createUser({
            variables: {
              name: formData.get('name'),
              email: formData.get('email')
            }
          });
        }}>
          <input name="name" placeholder="Name" required />
          <input name="email" type="email" placeholder="Email" required />
          <button type="submit" disabled={loading}>
            {loading ? 'Creating...' : 'Create User'}
          </button>
          {error && <p>Error: {error.message}</p>}
          {data && <p>User created: {data.createUser.name}</p>}
        </form>
      )}
    </Mutation>
  );
}

Architecture

Apollo React Components is built around a re-export wrapper pattern that provides compatibility and convenience for legacy Apollo GraphQL applications. The package architecture consists of:

  • Re-export Layer: This package serves as a thin wrapper that combines exports from two core Apollo Client modules
  • Component-based API: Primary focus on render prop components (Query, Mutation, Subscription) from @apollo/client/react/components
  • Full Apollo Client Integration: Complete re-export of @apollo/client core functionality including hooks, client, cache, and network layers
  • Deprecation Bridge: Acts as a compatibility layer during the transition from Apollo React Components to Apollo Client 3.0+

Design Patterns

The package supports two main GraphQL integration patterns:

  1. Component-based Pattern (Legacy): Uses render prop components for GraphQL operations

    • <Query>, <Mutation>, <Subscription> components
    • Declarative JSX-based approach
    • Legacy pattern deprecated in favor of hooks
  2. Hook-based Pattern (Modern): Uses React hooks for GraphQL operations

    • useQuery, useMutation, useSubscription hooks
    • More flexible and composable approach
    • Recommended pattern for new development

The re-export pattern ensures applications can access both approaches through a single import, facilitating gradual migration from components to hooks while maintaining full Apollo Client ecosystem compatibility.

Capabilities

Query Component

Executes GraphQL queries using a render prop pattern.

interface QueryProps<TData = any, TVariables = OperationVariables> {
  query: DocumentNode;
  variables?: TVariables;
  fetchPolicy?: FetchPolicy;
  errorPolicy?: ErrorPolicy;
  notifyOnNetworkStatusChange?: boolean;
  pollInterval?: number;
  skip?: boolean;
  onCompleted?: (data: TData) => void;
  onError?: (error: ApolloError) => void;
  children: (result: QueryResult<TData, TVariables>) => React.ReactNode;
}

interface QueryResult<TData = any, TVariables = OperationVariables> {
  data?: TData;
  loading: boolean;
  error?: ApolloError;
  networkStatus: NetworkStatus;
  refetch: (variables?: Partial<TVariables>) => Promise<ApolloQueryResult<TData>>;
  fetchMore: (options: FetchMoreQueryOptions<TVariables, TData>) => Promise<ApolloQueryResult<TData>>;
  startPolling: (pollInterval: number) => void;
  stopPolling: () => void;
  subscribeToMore: (options: SubscribeToMoreOptions<TData, TVariables, any>) => () => void;
  updateQuery: (updater: (prev: TData, options: UpdateQueryOptions<TVariables>) => TData) => void;
  client: ApolloClient<any>;
  called: boolean;
}

function Query<TData = any, TVariables = OperationVariables>(
  props: QueryProps<TData, TVariables>
): React.ReactElement;

Mutation Component

Executes GraphQL mutations using a render prop pattern.

interface MutationProps<TData = any, TVariables = OperationVariables> {
  mutation: DocumentNode;
  variables?: TVariables;
  errorPolicy?: ErrorPolicy;
  refetchQueries?: Array<string | PureQueryOptions> | RefetchQueriesFunction;
  awaitRefetchQueries?: boolean;
  update?: MutationUpdaterFn<TData>;
  onCompleted?: (data: TData) => void;
  onError?: (error: ApolloError) => void;
  children: (
    mutate: MutationFunction<TData, TVariables>,
    result: MutationResult<TData>
  ) => React.ReactNode;
}

interface MutationResult<TData = any> {
  data?: TData;
  loading: boolean;
  error?: ApolloError;
  called: boolean;
  client: ApolloClient<any>;
}

type MutationFunction<TData = any, TVariables = OperationVariables> = (
  options?: MutationFunctionOptions<TData, TVariables>
) => Promise<FetchResult<TData>>;

function Mutation<TData = any, TVariables = OperationVariables>(
  props: MutationProps<TData, TVariables>
): React.ReactElement;

Subscription Component

Handles GraphQL subscriptions using a render prop pattern.

interface SubscriptionProps<TData = any, TVariables = OperationVariables> {
  subscription: DocumentNode;
  variables?: TVariables;
  shouldResubscribe?: boolean;
  onSubscriptionData?: (options: OnSubscriptionDataOptions<TData>) => void;
  onSubscriptionComplete?: () => void;
  fetchPolicy?: FetchPolicy;
  errorPolicy?: ErrorPolicy;
  children: (result: SubscriptionResult<TData>) => React.ReactNode;
}

interface SubscriptionResult<TData = any> {
  data?: TData;
  loading: boolean;
  error?: ApolloError;
}

function Subscription<TData = any, TVariables = OperationVariables>(
  props: SubscriptionProps<TData, TVariables>
): React.ReactElement;

Re-exported Apollo Client Core

This package also re-exports all functionality from @apollo/client, including:

Client and Provider

class ApolloClient<TCacheShape> {
  constructor(options: ApolloClientOptions<TCacheShape>);
  query<T = any, TVariables = OperationVariables>(options: QueryOptions<TVariables, T>): Promise<ApolloQueryResult<T>>;
  mutate<T = any, TVariables = OperationVariables>(options: MutationOptions<T, TVariables>): Promise<FetchResult<T>>;
  subscribe<T = any, TVariables = OperationVariables>(options: SubscriptionOptions<TVariables, T>): Observable<FetchResult<T>>;
}

interface ApolloProviderProps<TCacheShape> {
  client: ApolloClient<TCacheShape>;
  children: React.ReactNode;
}

function ApolloProvider<TCacheShape>(props: ApolloProviderProps<TCacheShape>): React.ReactElement;

interface ApolloConsumerProps {
  children: (client: ApolloClient<any>) => React.ReactNode;
}

function ApolloConsumer(props: ApolloConsumerProps): React.ReactElement;

React Hooks

function useQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: QueryHookOptions<TData, TVariables>
): QueryResult<TData, TVariables>;

function useLazyQuery<TData = any, TVariables = OperationVariables>(
  query: DocumentNode,
  options?: LazyQueryHookOptions<TData, TVariables>
): [QueryLazyOptions<TVariables>, QueryResult<TData, TVariables>];

function useMutation<TData = any, TVariables = OperationVariables>(
  mutation: DocumentNode,
  options?: MutationHookOptions<TData, TVariables>
): [MutationFunction<TData, TVariables>, MutationResult<TData>];

function useSubscription<TData = any, TVariables = OperationVariables>(
  subscription: DocumentNode,
  options?: SubscriptionHookOptions<TData, TVariables>
): SubscriptionResult<TData>;

function useApolloClient(): ApolloClient<any>;

Cache

class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
  constructor(config?: InMemoryCacheConfig);
}

abstract class ApolloCache<TSerialized> {
  abstract read<T>(query: Cache.ReadOptions): T | null;
  abstract write(write: Cache.WriteOptions): void;
  abstract diff<T>(query: Cache.DiffOptions): Cache.DiffResult<T>;
  abstract watch(watch: Cache.WatchOptions): () => void;
}

Network Layer

class HttpLink extends ApolloLink {
  constructor(options?: HttpOptions);
}

function createHttpLink(options?: HttpOptions): HttpLink;

abstract class ApolloLink {
  static from(links: (ApolloLink | RequestHandler)[]): ApolloLink;
  static split(test: (op: Operation) => boolean, left: ApolloLink | RequestHandler, right?: ApolloLink | RequestHandler): ApolloLink;
  concat(next: ApolloLink | RequestHandler): ApolloLink;
}

GraphQL Utilities

function gql(literals: TemplateStringsArray, ...args: any[]): DocumentNode;

interface DocumentNode {
  kind: 'Document';
  definitions: ReadonlyArray<DefinitionNode>;
}

Error Handling

class ApolloError extends Error {
  message: string;
  graphQLErrors: ReadonlyArray<GraphQLError>;
  networkError: Error | null;
  extraInfo: any;
  constructor(options: ErrorOptions);
}

Types

type OperationVariables = Record<string, any>;

type FetchPolicy = 'cache-first' | 'cache-and-network' | 'network-only' | 'cache-only' | 'standby';

type ErrorPolicy = 'none' | 'ignore' | 'all';

type WatchQueryFetchPolicy = FetchPolicy | 'cache-and-network';

enum NetworkStatus {
  loading = 1,
  setVariables = 2,
  fetchMore = 3,
  refetch = 4,
  poll = 6,
  ready = 7,
  error = 8,
}

interface FetchResult<TData = Record<string, any>, TContext = Record<string, any>, TExtensions = Record<string, any>> {
  data?: TData;
  errors?: ReadonlyArray<GraphQLError>;
  extensions?: TExtensions;
  context?: TContext;
}

interface ApolloQueryResult<TData> {
  data: TData;
  errors?: ReadonlyArray<GraphQLError>;
  loading: boolean;
  networkStatus: NetworkStatus;
  partial?: boolean;
}

Migration Path

Current (Deprecated):

import { Query, Mutation, Subscription } from "@apollo/react-components";

Recommended (Apollo Client 3.0+):

// For components
import { Query, Mutation, Subscription } from "@apollo/client/react/components";

// Or use hooks directly (preferred)
import { useQuery, useMutation, useSubscription } from "@apollo/client";