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.

  • 7.0.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 💡

  • < 2.5 KB min+gzip bundle size, guaranteed by size-limit tests. That’s around 40 KB less than Apollo!
  • Native ESM via .mjs for Node.js in --experimental-modules mode and tree shaking bundlers like webpack.
  • Server side rendering for better UX and SEO.
  • Uses the React v16.3 context API.
  • All fetch options overridable per request.
  • GraphQL requests are cached under hashes of their fetch options:
    • No data normalization or need to query id fields.
    • No tampering with queries or __typename insertion.
    • Errors cache 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.pokemon.image} alt={name} />
          <figcaption>
            Pokémon #{data.pokemon.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.

Examples

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.
options.logErrorsboolean? = trueShould 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.

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)
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.

ParameterTypeDescription
childrenConsumerRenderRender function that receives a GraphQL instance.

Returns: ReactNode — React virtual DOM node.

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 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: ReactNode — React virtual DOM node.

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: ReactNode — React virtual DOM node.

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>
)

function ssr

Asynchronously server side renders a React node, preloading all Query components that have the loadOnMount prop. After resolving, cache can be exported from the GraphQL instance property cache for serialization (usually as JSON) and transport to the client for hydration via the GraphQL constructor parameter options.cache.

ParameterTypeDescription
graphqlGraphQLGraphQL instance.
nodeReactNodeReact virtual DOM node.
renderfunction? = ReactDOMServer.renderToStaticMarkupSynchronous React server side render function, defaulting to ReactDOMServer.renderToStaticMarkup as it is more efficient than ReactDOMServer.renderToString.

Returns: Promise<string> — Promise resolving the rendered HTML string.

See
Examples

SSR function that resolves a HTML string and cache JSON for client hydration.

import { GraphQL, Provider } from 'graphql-react'
import { ssr } from 'graphql-react/lib/ssr'
import ReactDOMServer from 'react-dom/server'
import { App } from './components'

async function render() {
  const graphql = new GraphQL()
  const page = (
    <Provider value={graphql}>
      <App />
    </Provider>
  )
  const html = await ssr(graphql, page, ReactDOMServer.renderToString)
  const cache = JSON.stringify(graphql.cache)
  return { html, cache }
}

SSR function that resolves a HTML string suitable for a static page.

import { GraphQL, Provider } from 'graphql-react'
import { ssr } from 'graphql-react/lib/ssr'
import { App } from './components'

function render() {
  const graphql = new GraphQL()
  const page = (
    <Provider value={graphql}>
      <App />
    </Provider>
  )
  return ssr(graphql, page)
}

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: ReactNode — React virtual DOM node.

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.
graphQLErrorsArray<Object>?GraphQL response errors.
dataObject?GraphQL response data.

Returns: ReactNode — React virtual DOM node.

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 ReactNode

React virtual DOM node; anything React can render.

Type: undefined | null | boolean | number | string | React.Element | Array<ReactNode>

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.
graphQLErrorsArray<Object>?GraphQL response errors.
dataObject?GraphQL response data.

Keywords

FAQs

Package last updated on 29 Jan 2019

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