@shopify/react-graphql
Tools for creating type-safe and asynchronous GraphQL components for React.
Last updated 17 days ago by shopify-dep .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install @shopify/react-graphql 
SYNC missed versions from official npm registry.

@shopify/react-graphql

Build Status License: MIT npm version npm bundle size (minified + gzip)

Tools for consuming GraphQL in a fun and type-safe way.

Installation

$ yarn add @shopify/react-graphql

Usage

This library builds on top of react-apollo. It provides alternatives to many of Apollo’s APIs, including useQuery and useMutation, to provide seamless and thorough type checking for query components whose types are generated by graphql-typescript-definitions. Additionally, it provides techniques for creating asynchronously loaded GraphQL queries that seamlessly interoperate with @shopify/react-async’s usePreload, usePrefetch, and useKeepFresh APIs.

Prerequisites

ApolloProvider

Before using the hooks and other utilities provided by this package, you must wrap your application in an ApolloProvider. This provider should be usedinstead of react-apollo's ApolloProvider, and it accepts the same props as that component.

import React from 'react';
import {render} from 'react-dom';

import ApolloClient from 'apollo-client';
import {ApolloProvider} from '@shopify/react-graphql';

const client = new ApolloClient();

export function App() {
  return (
    <ApolloProvider client={client}>
      <MyRootComponent />
    </ApolloProvider>
  );
}

Hooks

useQuery()

This hook accepts two arguments:

  • first argument, a required query document, or an AsyncQueryComponent created from createAsyncQueryComponent, or an async query create with createAsyncQuery.

  • second argument, a optional set of options with the following type definition.

interface QueryHookOptions<Variables = OperationVariables> {
  ssr?: boolean;
  variables?: Variables;
  fetchPolicy?: WatchQueryFetchPolicy;
  errorPolicy?: ErrorPolicy;
  pollInterval?: number;
  client?: ApolloClient<any>;
  notifyOnNetworkStatusChange?: boolean;
  context?: Context;
  skip?: boolean;
}

The hook result is an object with the type definition of:

interface QueryHookResult<Data, Variables> {
  client: ApolloClient<any>;
  data: Data | undefined;
  error?: ApolloError;
  loading: boolean;
  startPolling(pollInterval: number): void;
  stopPolling(): void;
  subscribeToMore<SubscriptionData = Data>(
    options: SubscribeToMoreOptions<Data, Variables, SubscriptionData>,
  ): () => void;
  updateQuery(
    mapFn: (
      previousQueryResult: Data,
      options: UpdateQueryOptions<Variables>,
    ) => Data,
  ): void;
  refetch(variables?: Variables): Promise<ApolloQueryResult<Data>>;
  networkStatus: NetworkStatus | undefined;
  variables: Variables | undefined;
}

useBackgroundQuery()

This hook is similar to useQuery, but instead of executing the query immediately, this hook returns a function that allows you to run the query on-demand at a later time. This makes it well-suited for prefetching a query, when you do not care about the actual result.

function MyComponent() {
  const runQuery = useBackgroundQuery(myQuery, {variables: {first: 10}});

  return (
    <button type="button" onTouchStart={runQuery}>
      Load
    </button>
  );
}

useMutation()

This hook accepts two arguments: the mutation document, and optionally, a set of options to pass to the underlying mutation. It will return a function that will trigger the mutation when invoked.

Note the set of options can be pass directly into the hook, or pass in while triggering the mutation function. If options exist in both places, they will be shallowly merge together with per-mutate options being the priority.

import React from 'react';
import {Form, TextField, Button, Banner} from '@shopify/polaris';
import {useMutation} from '@shopify/react-graphql';

import createCustomerMutation from './graphql/CreateCustomerMutation.graphql';

function CustomerDetail() {
  const [name, setName] = React.useState('');
  const createCustomer = useMutation(createCustomerMutation, {
    fetchPolicy: 'network-only',
  });

  async function handleFormSubmit() {
    try {
      await createCustomer({
        variables: {name},
      });

      // do something when the mutation is successful
    } catch (error) {
      // do something when the mutation fails
    }
  }

  return (
    <Form onSubmit={handleFormSubmit}>
      <TextField label="Name" value={name} onChange={(value) => {
        setName(value);
      }}>
      <Button submit>
        Create Customer
      </Button>
    </Form>
  );
}

useApolloClient()

useApolloClient hook can be use to access apollo client that is currently in the context. The client returned from hook can than be use to trigger query manually. Read ApolloClient class API for the full list of actions you can perform.

import React from 'react';
import gql from 'graphql-tag';
import {useApolloClient} from '@shopify/react-graphql';
import {Button} from '@shopify/polaris';

const petQuery = gql`
  query PetQuery {
    pets {
      name
    }
  }
`;

function MyComponent() {
  const client = useApolloClient();

  async function fetchPets() {
    try {
      await client.query({
        petQuery,
      });
    } catch (error) {
      throw error;
    }
  }

  return <Button onClick={fetchPets}>Fetch Pets</Button>;
}

Async queries

createAsyncQuery()

createAsyncQuery is used to create a GraphQL document that is only loaded when the query is actually run. This feature of the query makes it well-suited for use with prefetching, as you would otherwise need to include all prefetched GraphQL queries in the main bundle.

To create an async query, call createAsyncQuery with a load property that asyncronously loads a GraphQL document:

import {createAsyncQuery} from '@shopify/react-graphql';

const productDetailsQuery = createAsyncQuery({
  load: () => import('./graphql/ProductDetailsQuery.graphql'),
});

The returned value can be used in any of the other APIs of this library that accept a query document. Additionally, this value has @shopify/react-async-compatible usePreload, usePrefetch, and useKeepFresh hooks. That means the document can be preloaded, prefetched, or kept fresh (using polling) using the hooks provided by @shopify/react-async.

import {usePrefetch} from '@shopify/react-async';
import {createAsyncQuery, useQuery} from '@shopify/react-graphql';

const myQuery = createAsyncQuery({
  load: () => import('./graphql/MyQuery.graphql'),
});

// The result of calling the GraphQL query
const {data, loading} = useQuery(myQuery);

// A function that will load the query script and run the query immediately
// when called
const prefetch = usePrefetch(myQuery);

createAsyncQueryComponent()

This function uses createAsyncQuery with the provided arguments to create an async query, and returns a React component that will run the query when mounted. Like createAsyncQuery, the resulting component is strongly type checked, and is fully compatible with the usePreload-style hooks from @shopify/react-async.

import {createAsyncQueryComponent} from '@shopify/react-graphql';

const ProductDetailsQuery = createAsyncQueryComponent({
  load: () => import('./graphql/ProductDetailsQuery.graphql'),
});

This component can now be used just like a regular Query component. It accepts all the same props, except that the query (and associated types) are already embedded in it, so those do not need to be provided.

// Assuming the following GraphQL API:
//
// type Shop = {
//   id: String!
//   name: String!
// }

// type Query = {
//   shop: Shop!
// }
//
// and the following query:
//
// query MyQuery {
//   shop { id }
// }

import {createAsyncQueryComponent} from '@shopify/react-graphql';

const MyQuery = createAsyncQueryComponent({
  load: () => import('./graphql/MyQuery.graphql'),
});

// Will complain if you try to pass any variables, because they aren’t needed.
// Will also complain if you try to reference properties on `data` that are not
// available.
<MyQuery>
  {({data}) => {
    return data ? <div>{data.shop.id}</div> : null;
  }}
</MyQuery>;

As with components created by createAsyncQuery(), these queries also have static usePreload, usePrefetch, and useKeepFresh hooks. Like components create with ``@shopify/react-async, these components also have staticPreload,Prefetch, andKeepFresh` components.

import {usePrefetch} from '@shopify/react-async';
import {createAsyncQueryComponent} from '@shopify/react-graphql';

const MyQuery = createAsyncQueryComponent({
  load: () => import('./graphql/MyQuery.graphql'),
});

// Loads the query script when the browser is idle
<MyQuery.Preload />

// Loads the query script when the browser is idle, and starts polling the query
<MyQuery.KeepFresh pollInterval={20_000} />

// A function that will load the query script and run the query immediately
// when called
const prefetch = usePrefetch(MyQuery);

Components

Query

react-apollo’s Query component is great, but does not have any built-in understanding of the connection between a GraphQL operation (provided in the query prop) and the data types of the resulting query. This library re-exports a Query component with improved typings. It will automatically read from from the types embedded in the query by graphql-typescript-definitions and use these as appropriate for the rest of the Query component’s props.

import {Query} from '@shopify/react-graphql';
import myQuery from './graphql/MyQuery.graphql';

// Assuming the following GraphQL API:

//
// type Shop = {
//   id: String!
//   name: String!
// }

// type Query = {
//   shop: Shop!
// }
//
// and the following query:
//
// query MyQuery {
//   shop { id }
// }

// Type error because no variables are allowed
<Query query={query} variables={{}}>{() => null}</Query>

// Type error because name was not queried
<Query query={query}>
  {({data}) => {
    return data ? <div>{data.shop.name}</div> : null;
  }}
</Query>

Current Tags

  • 5.2.0-beta.4                                ...           beta (2 months ago)
  • 6.0.4                                ...           latest (17 days ago)

80 Versions

  • 6.0.4                                ...           17 days ago
  • 6.0.3                                ...           23 days ago
  • 6.0.2                                ...           a month ago
  • 6.0.1                                ...           a month ago
  • 6.0.0                                ...           a month ago
  • 5.2.5                                ...           a month ago
  • 5.2.4                                ...           a month ago
  • 5.2.3                                ...           2 months ago
  • 5.2.2                                ...           2 months ago
  • 5.2.1                                ...           2 months ago
  • 5.2.0                                ...           2 months ago
  • 5.1.5                                ...           2 months ago
  • 5.1.6                                ...           2 months ago
  • 5.2.0-beta.4                                ...           2 months ago
  • 5.2.0-beta.3                                ...           3 months ago
  • 5.2.0-beta.2                                ...           3 months ago
  • 5.2.0-beta.1                                ...           3 months ago
  • 5.2.0-alpha.2                                ...           3 months ago
  • 5.2.0-alpha.1                                ...           3 months ago
  • 5.1.4                                ...           3 months ago
  • 5.1.3                                ...           3 months ago
  • 5.1.2                                ...           3 months ago
  • 5.1.1                                ...           3 months ago
  • 5.1.0                                ...           3 months ago
  • 5.0.10                                ...           3 months ago
  • 5.0.9                                ...           3 months ago
  • 5.0.8                                ...           3 months ago
  • 5.0.6                                ...           3 months ago
  • 5.0.5                                ...           3 months ago
  • 5.0.3                                ...           3 months ago
  • 5.0.2                                ...           4 months ago
  • 5.0.1                                ...           4 months ago
  • 5.0.0                                ...           4 months ago
  • 4.0.7                                ...           4 months ago
  • 4.0.6                                ...           4 months ago
  • 4.0.5                                ...           4 months ago
  • 4.0.4                                ...           4 months ago
  • 4.0.3                                ...           4 months ago
  • 4.0.2                                ...           5 months ago
  • 4.0.1                                ...           5 months ago
  • 4.0.0                                ...           5 months ago
  • 3.4.3                                ...           5 months ago
  • 3.4.2                                ...           6 months ago
  • 3.4.1                                ...           6 months ago
  • 3.4.0                                ...           6 months ago
  • 3.3.6                                ...           6 months ago
  • 3.3.5                                ...           6 months ago
  • 3.3.4                                ...           7 months ago
  • 3.3.3                                ...           7 months ago
  • 3.3.2                                ...           7 months ago
  • 3.3.1                                ...           7 months ago
  • 3.3.0                                ...           7 months ago
  • 3.2.2                                ...           7 months ago
  • 3.2.1                                ...           7 months ago
  • 3.2.0                                ...           7 months ago
  • 3.1.2                                ...           7 months ago
  • 3.1.1                                ...           8 months ago
  • 3.1.0                                ...           8 months ago
  • 3.0.3                                ...           8 months ago
  • 3.0.2                                ...           8 months ago
  • 3.0.1                                ...           8 months ago
  • 3.0.0                                ...           8 months ago
  • 2.0.6                                ...           8 months ago
  • 2.0.5                                ...           8 months ago
  • 2.0.4                                ...           8 months ago
  • 2.0.3                                ...           9 months ago
  • 2.0.2                                ...           9 months ago
  • 2.0.1                                ...           9 months ago
  • 2.0.0                                ...           9 months ago
  • 1.3.6                                ...           9 months ago
  • 1.3.4                                ...           9 months ago
  • 1.3.3                                ...           9 months ago
  • 1.3.2                                ...           9 months ago
  • 1.3.1                                ...           9 months ago
  • 1.3.0                                ...           9 months ago
  • 1.2.0                                ...           10 months ago
  • 1.1.1                                ...           10 months ago
  • 1.1.0                                ...           10 months ago
  • 1.0.1                                ...           10 months ago
  • 1.0.0                                ...           10 months ago

Copyright 2014 - 2017 © taobao.org |