Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-react

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-react

A lightweight GraphQL client for React.

  • 4.1.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.9K
increased by54.71%
Maintainers
1
Weekly downloads
 
Created
Source

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 🔥

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.

ParameterTypeDescription
optionsObject? = {}Options.
options.cacheObject? = {}Cache to import; usually from a server side render.
Examples

Constructing a new GraphQL client.

import { GraphQL } from 'graphql-react'

const graphql = new GraphQL()
GraphQL instance method query

Queries a GraphQL server.

ParameterTypeDescription
optionsObjectOptions.
options.operationGraphQLOperationGraphQL operation.
options.fetchOptionsOverrideFetchOptionsOverride?Overrides default GraphQL request fetch options.
options.resetOnLoadboolean? = falseShould 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.

ParameterTypeDescription
exceptFetchOptionsHashstring?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)

function Consumer

A React component that gets the GraphQL instance from context.

ParameterTypeDescription
childrenConsumerRenderRender 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.

ParameterTypeDescription
elementReactElementA 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.

ParameterTypeDescription
valueGraphQLA GraphQL instance.
childrenReactNodeA 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.

ParameterTypeDescription
propsObjectComponent props.
props.operationGraphQLOperationGraphQL operation.
props.fetchOptionsOverrideFetchOptionsOverride?Overrides default GraphQL request fetch options.
props.loadOnMountboolean? = falseShould the query load when the component mounts.
props.loadOnResetboolean? = falseShould the query load when the GraphQL cache is reset.
props.resetOnLoadboolean? = falseShould the GraphQL cache reset when the query loads.
props.childrenQueryRenderRenders 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

PropertyTypeDescription
fetchOptionsHashstringfetch options hash.
cacheRequestCache?Results from the last identical request.
requestPromise<RequestCache>A promise that resolves fresh request cache.

type ConsumerRender

Renders a GraphQL consumer.

Type: function

ParameterTypeDescription
graphqlGraphQLGraphQL 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

PropertyTypeDescription
urlstringA GraphQL API URL.
bodystring | FormDataHTTP request body.
headersObjectHTTP request headers.
credentialsstring?Authentication credentials mode.

type FetchOptionsOverride

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

Type: function

ParameterTypeDescription
fetchOptionsFetchOptionsDefault GraphQL request fetch options.
operationGraphQLOperation?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

PropertyTypeDescription
querystringGraphQL queries or mutations.
variablesObjectVariables used by the query.

type HttpError

Fetch HTTP error.

Type: Object

PropertyTypeDescription
statusnumberHTTP status code.
statusTextstringHTTP status text.

type QueryRender

Renders the status of a query or mutation.

Type: function

ParameterTypeDescription
loadfunctionLoads the query on demand, updating cache.
loadingbooleanIs the query loading.
fetchErrorstring?Fetch error message.
httpErrorHttpError?Fetch response HTTP error.
parseErrorstring?Parse error message.
graphQLErrorsObject?GraphQL response errors.
dataObject?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

PropertyTypeDescription
fetchErrorstring?Fetch error message.
httpErrorHttpError?Fetch response HTTP error.
parseErrorstring?Parse error message.
graphQLErrorsObject?GraphQL response errors.
dataObject?GraphQL response data.

Keywords

FAQs

Package last updated on 01 Nov 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc