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.

  • 0.1.0
  • Source
  • npm
  • Socket score

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

Logo

graphql-react

npm version Licence Github issues Github stars

A lightweight GraphQL client for React.

⚠️ SSR API coming soon.

Easy 🤹
  • 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.
Smart 👨‍🔬
  • Adds ~ 4 KB to a typical min+gzip bundle.
  • Native ESM in Node.js via .mjs.
  • Package module entry for tree shaking bundlers.
  • Components use the React v16.3 context API.
  • All fetch options overridable per request.
  • Request hash based cache:
    • No data denormalization and no need to query id fields.
    • No tampering with queries or __typename insertion.
    • Query multiple GraphQL services without stitching data.
    • Errors also cache, enabling error SSR.

Setup

Install with npm:

npm install graphql-react

Create and provide a GraphQL client:

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

const graphql = new GraphQL()

const Page = () => (
  <GraphQLProvider value={graphql}>
    <!-- Now use GraphQLQuery or GraphQLMutation components -->
  </GraphQLProvider>
)

Example

See the example Next.js app and GraphQL API.

API

Table of Contents

GraphQLQuery

A React component to manage a GraphQL query.

Parameters

  • props Object Component props.
    • props.variables Object? GraphQL query variables.
    • props.query String GraphQL query.
    • props.loadOnMount Boolean Should the query load when the component mounts. (optional, default true)
    • props.loadOnReset Boolean Should the query load when the GraphQL client cache is reset. (optional, default true)
    • props.resetOnLoad Boolean Should the GraphQL client cache reset when the query loads. (optional, default false)
  • children Function Render function.

Examples

import { GraphQLQuery } from 'graphql-react'

const Profile = ({ userId }) => (
  <GraphQLQuery
    variables={{ userId }}
    query={`
      query user($userId: ID!) {
        user(userId: $id) {
          name
        }
      }
    `}
  >
    {({ load, loading, httpError, parseError, graphQLErrors, data }) => (
      <article>
        {loading && <span>Loading…</span>}
        {(httpError || parseError || graphQLErrors) && <strong>Error!</strong>}
        {data && <h1>{data.user.name}</h1>}
        <button onClick={load} disabled={loading}>
          Reload
        </button>
      </article>
    )}
  </GraphQLQuery>
)

Returns String HTML.

GraphQLMutation

A React component to manage a GraphQL mutation. The same as GraphQLQuery but with different default props.

Parameters

  • props Object Component props.
    • props.variables Object? GraphQL query variables.
    • props.query String GraphQL query.
    • props.loadOnMount Boolean Should the query load when the component mounts. (optional, default false)
    • props.loadOnReset Boolean Should the query load when the GraphQL client cache is reset. (optional, default false)
    • props.resetOnLoad Boolean Should the GraphQL client cache reset when the query loads. (optional, default true)
  • children Function Render function.

Examples

import { GraphQLMutation } from 'graphql-react'

const ClapArticleButton = ({ articleId }) => (
  <GraphQLMutation
    variables={{ articleId }}
    query={`
      mutation clapArticle($articleId: ID!) {
        clapArticle(articleId: $id) {
          clapCount
        }
      }
    `}
  >
    {({ load, loading, httpError, parseError, graphQLErrors, data }) => (
      <aside>
        {(httpError || parseError || graphQLErrors) && <strong>Error!</strong>}
        {data && <p>Clapped {data.clapArticle.clapCount} times.</p>}
        <button onClick={load} disabled={loading}>
          Clap
        </button>
      </aside>
    )}
  </GraphQLMutation>
)

Returns String HTML.

GraphQL

A lightweight GraphQL client with a request cache.

Parameters

  • options Object Options. (optional, default {})
    • options.cache Object Cache to import; useful once a SSR API is available. (optional, default {})
    • options.requestOptions RequestOptionsOverride? A function that accepts and modifies generated options for every request.

Examples

const graphql = new GraphQL({
  requestOptions: options => {
    options.url = 'https://api.example.com/graphql'
    options.credentials = 'include'
  }
})
reset

Resets the cache. Useful when a user logs out.

Examples

graphql.reset()
query

Queries a GraphQL server.

Parameters

  • operation Operation GraphQL operation object.

Returns ActiveQuery In-flight query details.

RequestCache

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

Type: Object

Properties

  • httpError Object HTTP error.
    • httpError.status String HTTP status code.
    • httpError.statusText String HTTP status text.
  • parseError String Parse error message.
  • graphQLErrors Object GraphQL response errors.
  • data Object GraphQL response data.

RequestCachePromise

A promise for an in-flight query that resolves the request cache.

Type: Promise<RequestCache>

ActiveQuery

Type: Object

Properties

RequestOptionsOverride

A way to override request options generated for a fetch. Modify the provided options object directly; no return.

Type: Function

Parameters

Examples

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

CacheUpdateCallback

A cache update listener callback.

Type: Function

Parameters

RequestOptions

Options for a GraphQL fetch request. See polyfillable fetch options.

Type: Object

Properties

  • url String A GraphQL API URL.
  • body (String | FormData) HTTP request body.
  • headers Object HTTP request headers.
  • credentials String? Authentication credentials mode.

Operation

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

Type: Object

Properties

  • query String GraphQL queries or mutations.
  • variables Object Variables used by the query.

Support

Keywords

FAQs

Package last updated on 23 Feb 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