A lightweight GraphQL client for React.
Clone or download
Latest commit f917273 Dec 3, 2018

readme.md

graphql-react logo

graphql-react

npm version Build status

A lightweight GraphQL client for React; the first Relay and Apollo alternative with server side rendering.

Easy 🔥

  • Add 1 dependency to get started with GraphQL in a React project.
  • No Webpack or Babel setup.
  • Simple components, no decorators.
  • Query components fetch on mount and when props change. While loading, cache from the last identical request is available to display.
  • Automatically fresh cache, even after mutations.
  • Use file input values as mutation arguments to upload files; compatible with a variety of servers.
  • Template literal queries; no need for gql.
  • Query multiple GraphQL APIs.

Smart 💡

  • Adds only a few KB to a typical min+gzip bundle.
  • Native ESM in Node.js via .mjs.
  • Package module entry for tree shaking bundlers.
  • Server side rendering for crawlable pages and a better UX.
  • Components use the React v16.3 context API.
  • All fetch options overridable per request.
  • GraphQL request fetch options hash based cache:
    • No data denormalization or need to query id fields.
    • No tampering with queries or __typename insertion.
    • Errors are cached and can be server side rendered.
    • Query multiple GraphQL APIs without stitching data.

Setup

To install graphql-react from npm run:

npm install graphql-react

Create and provide a single GraphQL client to hold the cache for all the queries in your app:

import { GraphQL, Provider } from 'graphql-react'

const graphql = new GraphQL()

export const App = ({ children }) => (
  <Provider value={graphql}>{children}</Provider>
)

GraphQL accepts a single cache option for hydration after SSR; see Example.

Setup is simple because Query components determine their own fetch options (such as the GraphQL endpoint URI). Multiple GraphQL APIs can be used in an app 🤯

Usage

Use the Query component for queries and mutations throughout your app:

import { Query } from 'graphql-react'

export const PokemonViewer = ({ name }) => (
  <Query
    loadOnMount
    loadOnReset
    fetchOptionsOverride={options => {
      options.url = 'https://graphql-pokemon.now.sh'
    }}
    operation={{
      variables: { name },
      query: /* GraphQL */ `
        query pokemon($name: String!) {
          pokemon(name: $name) {
            number
            image
          }
        }
      `
    }}
  >
    {({ loading, data }) =>
      data ? (
        <figure>
          <img src={data.image} alt={name} />
          <figcaption>
            Pokémon #{data.number}: {name}
          </figcaption>
        </figure>
      ) : loading ? (
        <p>Loading…</p>
      ) : (
        <p>Error!</p>
      )
    }
  </Query>
)

To make queries and mutations without a component, use the GraphQL instance method query.

Example

See the example GraphQL API and Next.js web app, deployed at graphql-react.now.sh.

Support

Consider polyfilling:

API

Table of contents

class GraphQL

A lightweight GraphQL client that caches requests.

Parameter Type Description
options Object? = {} Options.
options.cache Object? = {} Cache to import; usually from a server side render.
options.logErrors boolean? = true Should GraphQL request errors be console logged for easy debugging.

Examples

Constructing a new GraphQL client.

import { GraphQL } from 'graphql-react'

const graphql = new GraphQL()

GraphQL instance method query

Queries a GraphQL server.

Parameter Type Description
options Object Options.
options.operation GraphQLOperation GraphQL operation.
options.fetchOptionsOverride FetchOptionsOverride? Overrides default GraphQL request fetch options.
options.resetOnLoad boolean? = false Should the GraphQL cache reset when the query loads.

Returns: ActiveQuery — Loading query details.

GraphQL instance method reset

Resets the GraphQL cache. Useful when a user logs out.

Parameter Type Description
exceptFetchOptionsHash string? A fetch options hash for cache to exempt from deletion. Useful for resetting cache after a mutation, preserving the mutation cache.
Examples

Resetting the GraphQL cache.

graphql.reset()

GraphQL instance property cache

GraphQL request cache map, keyed by fetch options hashes.

Examples

Export cache as JSON.

const exportedCache = JSON.stringify(graphql.cache)

GraphQL instance property logErrors

Should GraphQL request errors be logged. May be toggled at runtime.

function Consumer

A React component that gets the GraphQL instance from context.

Parameter Type Description
children ConsumerRender Render function that receives a GraphQL instance.

Returns: ReactElement — React virtual DOM element.

Examples

A button component that resets the GraphQL cache.

import { Consumer } from 'graphql-react'

const ResetCacheButton = () => (
  <Consumer>
    {graphql => <button onClick={graphql.reset}>Reset cache</button>}
  </Consumer>
)

function preload

Recursively preloads Query components that have the loadOnMount prop in a React element tree. Useful for server side rendering (SSR) or to preload components for a better user experience when they mount.

Parameter Type Description
element ReactElement A React virtual DOM element.

Returns: Promise — Resolves once loading is done and cache is ready to be exported from the GraphQL instance. Cache can be imported when constructing new GraphQL instances.

Examples

An async SSR function that returns a HTML string and cache JSON for client hydration.

import { GraphQL, preload, Provider } from 'graphql-react'
import { renderToString } from 'react-dom/server'
import { App } from './components'

const graphql = new GraphQL()
const page = (
  <Provider value={graphql}>
    <App />
  </Provider>
)

export async function ssr() {
  await preload(page)
  return {
    cache: JSON.stringify(graphql.cache),
    html: renderToString(page)
  }
}

function Provider

A React component that provides a GraphQL instance in context for nested Consumer components to use.

Parameter Type Description
value GraphQL A GraphQL instance.
children ReactNode A React node.

Returns: ReactElement — React virtual DOM element.

Examples

Using the Provider component for a page.

import { GraphQL, Provider } from 'graphql-react'

const graphql = new GraphQL()

const Page = () => (
  <Provider value={graphql}>Use Consumer or Query components…</Provider>
)

function Query

A React component to manage a GraphQL query or mutation.

Parameter Type Description
props Object Component props.
props.operation GraphQLOperation GraphQL operation.
props.fetchOptionsOverride FetchOptionsOverride? Overrides default GraphQL request fetch options.
props.loadOnMount boolean? = false Should the query load when the component mounts.
props.loadOnReset boolean? = false Should the query load when the GraphQL cache is reset.
props.resetOnLoad boolean? = false Should the GraphQL cache reset when the query loads.
props.children QueryRender Renders the query status.

Returns: ReactElement — React virtual DOM element.

Examples

A query to display a user profile.

import { Query } from 'graphql-react'

const Profile = ({ userId }) => (
  <Query
    loadOnMount
    loadOnReset
    fetchOptionsOverride={options => {
     options.url = 'https://api.example.com/graphql'
    }}
    operation={
      variables: { userId },
      query: `
        query user($userId: ID!) {
          user(userId: $userId) {
            name
          }
        }
      `
    }
  >
    {({
      load,
      loading,
      fetchError,
      httpError,
      parseError,
      graphQLErrors,
      data
    }) => (
      <article>
        <button onClick={load}>Reload</button>
        {loading && <span>Loading…</span>}
        {(fetchError || httpError || parseError || graphQLErrors) && (
          <strong>Error!</strong>
        )}
        {data && <h1>{data.user.name}</h1>}
      </article>
    )}
  </Query>
)

A mutation to clap an article.

import { Query } from 'graphql-react'

const ClapArticleButton = ({ articleId }) => (
  <Query
    resetOnLoad
    fetchOptionsOverride={options => {
      options.url = 'https://api.example.com/graphql'
    }}
    operation={
      variables: { articleId },
      query: `
        mutation clapArticle($articleId: ID!) {
          clapArticle(articleId: $articleId) {
            clapCount
          }
        }
      `
    }
  >
    {({
      load,
      loading,
      fetchError,
      httpError,
      parseError,
      graphQLErrors,
      data
    }) => (
      <aside>
        <button onClick={load} disabled={loading}>
          Clap
        </button>
        {(fetchError || httpError || parseError || graphQLErrors) && (
          <strong>Error!</strong>
        )}
        {data && <p>Clapped {data.clapArticle.clapCount} times.</p>}
      </aside>
    )}
  </Query>
)

type ActiveQuery

Loading query details.

Type: Object

Property Type Description
fetchOptionsHash string fetch options hash.
cache RequestCache? Results from the last identical request.
request Promise<RequestCache> A promise that resolves fresh request cache.

type ConsumerRender

Renders a GraphQL consumer.

Type: function

Parameter Type Description
graphql GraphQL GraphQL instance.

Returns: ReactElement — React virtual DOM element.

Examples

A button that resets the GraphQL cache.

graphql => <button onClick={graphql.reset}>Reset cache</button>

type FetchOptions

Polyfillable fetch options for a GraphQL request.

Type: Object

Property Type Description
url string A GraphQL API URL.
body string | FormData HTTP request body.
headers Object HTTP request headers.
credentials string? Authentication credentials mode.

type FetchOptionsOverride

Overrides default GraphQL request fetch options. Modify the provided options object without a return.

Type: function

Parameter Type Description
fetchOptions FetchOptions Default GraphQL request fetch options.
operation GraphQLOperation? GraphQL operation.

Examples

Setting fetch options for an example API.

options => {
  options.url = 'https://api.example.com/graphql'
  options.credentials = 'include'
}

type GraphQLOperation

A GraphQL operation. Additional properties may be used; all are sent to the GraphQL server.

Type: Object

Property Type Description
query string GraphQL queries or mutations.
variables Object Variables used by the query.

type HttpError

Fetch HTTP error.

Type: Object

Property Type Description
status number HTTP status code.
statusText string HTTP status text.

type QueryRender

Renders the status of a query or mutation.

Type: function

Parameter Type Description
load function Loads the query on demand, updating cache.
loading boolean Is the query loading.
fetchError string? Fetch error message.
httpError HttpError? Fetch response HTTP error.
parseError string? Parse error message.
graphQLErrors Object? GraphQL response errors.
data Object? GraphQL response data.

Returns: ReactElement — React virtual DOM element.

Examples

Rendering a user profile query.

;({
  load,
  loading,
  fetchError,
  httpError,
  parseError,
  graphQLErrors,
  data
}) => (
  <aside>
    <button onClick={load}>Reload</button>
    {loading && <span>Loading…</span>}
    {(fetchError || httpError || parseError || graphQLErrors) && (
      <strong>Error!</strong>
    )}
    {data && <h1>{data.user.name}</h1>}
  </aside>
)

type RequestCache

JSON serializable result of a GraphQL request (including all errors and data) suitable for caching.

Type: Object

Property Type Description
fetchError string? Fetch error message.
httpError HttpError? Fetch response HTTP error.
parseError string? Parse error message.
graphQLErrors Object? GraphQL response errors.
data Object? GraphQL response data.