All Projects → jaydenseric → Graphql React

jaydenseric / Graphql React

A GraphQL client for React using modern context and hooks APIs that is lightweight (< 3.5 KB size limited) but powerful; the first Relay and Apollo alternative with server side rendering.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Graphql React

Graphql Upload
Middleware and an Upload scalar to add support for GraphQL multipart requests (file uploads via queries and mutations) to various Node.js GraphQL servers.
Stars: ✭ 1,071 (+75.29%)
Mutual labels:  graphql, featured
Write With Me
Real-time Collaborative Markdown Editor
Stars: ✭ 81 (-86.74%)
Mutual labels:  graphql, hooks
Graphql Multipart Request Spec
A spec for GraphQL multipart form requests (file uploads).
Stars: ✭ 622 (+1.8%)
Mutual labels:  graphql, featured
Dahlia
An opinionated React Framework. [Rename to pea.js]
Stars: ✭ 92 (-84.94%)
Mutual labels:  graphql, hooks
Googlekeepclone
A clone of Google Keep with its original Material Design aesthetics
Stars: ✭ 281 (-54.01%)
Mutual labels:  graphql, hooks
Relay Hooks
Use Relay as React hooks
Stars: ✭ 423 (-30.77%)
Mutual labels:  graphql, hooks
Apollo Upload Client
A terminating Apollo Link for Apollo Client that allows FileList, File, Blob or ReactNativeFile instances within query or mutation variables and sends GraphQL multipart requests.
Stars: ✭ 1,176 (+92.47%)
Mutual labels:  graphql, featured
Platform Samples
A public place for all platform sample projects.
Stars: ✭ 1,328 (+117.35%)
Mutual labels:  graphql, hooks
Graphql Hooks
🎣 Minimal hooks-first GraphQL client
Stars: ✭ 1,610 (+163.5%)
Mutual labels:  graphql, hooks
React Query
⚛️ Hooks for fetching, caching and updating asynchronous data in React
Stars: ✭ 24,427 (+3897.87%)
Mutual labels:  graphql, hooks
Animavita
Trigger life-saving alerts, register animals for adoption and find the closest pet friend to adopt 🐶
Stars: ✭ 508 (-16.86%)
Mutual labels:  graphql, hooks
Neo4j Graphql Js
A GraphQL to Cypher query execution layer for Neo4j and JavaScript GraphQL implementations.
Stars: ✭ 585 (-4.26%)
Mutual labels:  graphql
Pluggy
A minimalist production ready plugin system
Stars: ✭ 572 (-6.38%)
Mutual labels:  hooks
Stop Runaway React Effects
🏃 Catches situations when a react use(Layout)Effect runs repeatedly in rapid succession
Stars: ✭ 574 (-6.06%)
Mutual labels:  hooks
Kretes
A Programming Environment for TypeScript & Node.js built on top of VS Code
Stars: ✭ 570 (-6.71%)
Mutual labels:  graphql
Awesome Aws Appsync
Curated list of AWS AppSync Resources
Stars: ✭ 594 (-2.78%)
Mutual labels:  graphql
Graphqldesigner.com
A developer web-app tool to rapidly prototype a full stack implementation of GraphQL with React.
Stars: ✭ 587 (-3.93%)
Mutual labels:  graphql
Damn Vulnerable Graphql Application
Damn Vulnerable GraphQL Application is an intentionally vulnerable implementation of Facebook's GraphQL technology, to learn and practice GraphQL Security.
Stars: ✭ 567 (-7.2%)
Mutual labels:  graphql
Pup
The Ultimate Boilerplate for Products.
Stars: ✭ 563 (-7.86%)
Mutual labels:  graphql
React Fetching Library
Simple and powerful API client for react 👍 Use hooks or FACCs to fetch data in easy way. No dependencies! Just react under the hood.
Stars: ✭ 561 (-8.18%)
Mutual labels:  hooks

graphql-react logo

graphql-react

npm version CI status

A GraphQL client for React using modern context and hooks APIs that is lightweight (< 3.5 KB size limited) but powerful; the first Relay and Apollo alternative with server side rendering.

Setup

First, polyfill any required globals (see Support) that are missing in your client and server environments.

Next.js setup

See the next-graphql-react setup instructions.

Vanilla React setup

To install graphql-react from npm run:

npm install graphql-react

Create a single GraphQL instance and use GraphQLProvider to provide it for your app.

To server side render your app, use the function waterfallRender from react-waterfall-render.

Usage

Use the useGraphQL React hook in your components to make queries and mutations, or use the GraphQL instance method operate directly.

Examples

Here is a basic example using the GitHub GraphQL API, with tips commented:

import { GraphQL, GraphQLProvider, useGraphQL } from 'graphql-react';
import React from 'react';

// Any GraphQL API can be queried in components, where fetch options for the
// URI, auth headers, etc. can be specified. The `useGraphQL` hook will do less
// work for following renders if `fetchOptionsOverride` is defined outside the
// component, or is memoized using the `React.useMemo` hook within the
// component. Typically it’s exported in a config module for use throughout the
// project. The default fetch options received by the override function are
// tailored to the operation; usually the body is JSON but if there are files in
// the variables it will be a `FormData` instance for a GraphQL multipart
// request.
function fetchOptionsOverride(options) {
  options.url = 'https://api.github.com/graphql';
  options.headers.Authorization = `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`;
}

// The query is just a string; no need to use `gql` from `graphql-tag`. The
// special comment before the string allows editor syntax highlighting, Prettier
// formatting and linting. The cache system doesn’t require `__typename` or `id`
// fields to be queried.
const query = /* GraphQL */ `
  query($repoId: ID!) {
    repo: node(id: $repoId) {
      ... on Repository {
        stargazers {
          totalCount
        }
      }
    }
  }
`;

function RepoStarCount({ repoId }) {
  // Memoization allows the `useGraphQL` hook to avoid work in following renders
  // with the same GraphQL operation.
  const operation = React.useMemo(
    () => ({
      query,
      variables: {
        repoId,
      },
    }),
    [repoId]
  );

  // The `useGraphQL` hook can be used for both queries and mutations.
  const { loading, cacheValue } = useGraphQL({
    operation,
    fetchOptionsOverride,

    // Load the query whenever the component mounts. This is desirable for
    // queries to display content, but not for on demand situations like
    // pagination view more buttons or forms that submit mutations.
    loadOnMount: true,

    // Reload the query whenever a global cache reload is signaled.
    loadOnReload: true,

    // Reload the query whenever the global cache is reset. Resets immediately
    // delete the cache and are mostly only used when logging out the user.
    loadOnReset: true,
  });

  return cacheValue?.data
    ? cacheValue.data.repo.stargazers.totalCount
    : loading
    ? // Data is often reloaded, so don’t assume loading indicates no data.
      'Loading…'
    : // Detailed error info is available in the `cacheValue` properties
      // `fetchError`, `httpError`, `parseError` and `graphQLErrors`. A
      // combination of errors is possible, and an error doesn’t necessarily
      // mean data is unavailable.
      'Error!';
}

// Zero config GraphQL client that manages the cache.
const graphql = new GraphQL();

const App = () => (
  <GraphQLProvider graphql={graphql}>
    <RepoStarCount repoId="MDEwOlJlcG9zaXRvcnkxMTk5Mzg5Mzk=" />
  </GraphQLProvider>
);

Support

Consider polyfilling:

API

Table of contents

class GraphQL

A lightweight GraphQL client that caches queries and mutations.

Parameter Type Description
options object? = {} Options.
options.cache GraphQLCache? = {} Cache to import; usually from a server side render.

See

Examples

Ways to import.

import { GraphQL } from 'graphql-react';
import GraphQL from 'graphql-react/public/GraphQL.js';

Ways to require.

const { GraphQL } = require('graphql-react');
const GraphQL = require('graphql-react/public/GraphQL');

Construct a GraphQL client.

import { GraphQL } from 'graphql-react';

const graphql = new GraphQL();

GraphQL instance method off

Removes an event listener.

Parameter Type Description
type string Event type.
handler Function Event handler.

GraphQL instance method on

Adds an event listener.

Parameter Type Description
type string Event type.
handler Function Event handler.
See

GraphQL instance method operate

Loads a GraphQL operation, visible in GraphQL operations. Emits a GraphQL fetch event once the GraphQL operations has been updated, and a GraphQL cache event once it’s loaded into the GraphQL cache.

Parameter Type Description
options object Options.
options.operation GraphQLOperation GraphQL operation.
options.fetchOptionsOverride GraphQLFetchOptionsOverride? Overrides default GraphQL operation fetch options.
options.cacheKeyCreator GraphQLCacheKeyCreator? = hashObject GraphQL cache key creator for the operation.
options.reloadOnLoad boolean? = false Should a GraphQL reload happen after the operation loads, excluding the loaded operation cache.
options.resetOnLoad boolean? = false Should a GraphQL reset happen after the operation loads, excluding the loaded operation cache.

Returns: GraphQLOperationLoading — Loading GraphQL operation details.

Fires

GraphQL instance method reload

Signals that GraphQL cache subscribers such as the useGraphQL React hook should reload their GraphQL operation.

Parameter Type Description
exceptCacheKey GraphQLCacheKey? A GraphQL cache key for cache to exempt from reloading.
Fires
Examples

Reloading the GraphQL cache.

graphql.reload();

GraphQL instance method reset

Resets the GraphQL cache, useful when a user logs out.

Parameter Type Description
exceptCacheKey GraphQLCacheKey? A GraphQL cache key for cache to exempt from deletion. Useful for resetting cache after a mutation, preserving the mutation cache.
Fires
Examples

Resetting the GraphQL cache.

graphql.reset();

GraphQL instance property cache

Cache of loaded GraphQL operations. You probably don’t need to interact with this unless you’re implementing a server side rendering framework.

Type: GraphQLCache

Examples

Export cache as JSON.

const exportedCache = JSON.stringify(graphql.cache);

Example cache JSON.

{
  "a1bCd2": {
    "data": {
      "viewer": {
        "name": "Jayden Seric"
      }
    }
  }
}

GraphQL instance property operations

A map of loading GraphQL operations, listed under their GraphQL cache key in the order they were initiated. You probably don’t need to interact with this unless you’re implementing a server side rendering framework.

Type: object<GraphQLCacheKey, Array<Promise<GraphQLCacheValue>>>

Examples

How to await all loading GraphQL operations.

await Promise.all(Object.values(graphql.operations).flat());

GraphQL event cache

Signals that a GraphQL operation was fetched and cached.

Type: object

Property Type Description
cacheKey GraphQLCacheKey The GraphQL cache key for the operation that was cached.
cacheValue GraphQLCacheValue The loaded GraphQL cache value.
response Response? The Response instance; may be undefined if there was a fetch error.

GraphQL event fetch

Signals that a GraphQL operation is being fetched.

Type: object

Property Type Description
cacheKey GraphQLCacheKey The GraphQL cache key for the operation being fetched.
cacheValuePromise Promise<GraphQLCacheValue> Resolves the loaded GraphQL cache value.

GraphQL event reload

Signals that GraphQL cache subscribers such as the useGraphQL React hook should reload their GraphQL operation.

Type: object

Property Type Description
exceptCacheKey GraphQLCacheKey? A GraphQL cache key for cache to exempt from reloading.

GraphQL event reset

Signals that the GraphQL cache has been reset.

Type: object

Property Type Description
exceptCacheKey GraphQLCacheKey? The GraphQL cache key for cache that was exempted from deletion.

function GraphQLProvider

A React component that provides a GraphQL instance for an app.

Parameter Type Description
props object Component props.
props.graphql GraphQL GraphQL instance.
props.children ReactNode? React children.

Returns: ReactNode — React virtual DOM node.

See

  • GraphQLContext is provided via this component.
  • useGraphQL React hook requires this component to be an ancestor to work.

Examples

Ways to import.

import { GraphQLProvider } from 'graphql-react';
import GraphQLProvider from 'graphql-react/public/GraphQLProvider.js';

Ways to require.

const { GraphQLProvider } = require('graphql-react');
const GraphQLProvider = require('graphql-react/public/GraphQLProvider');

Provide a GraphQL instance for an app.

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

const graphql = new GraphQL();

const App = ({ children }) => (
  <GraphQLProvider graphql={graphql}>{children}</GraphQLProvider>
);

function hashObject

Hashes an object.

Parameter Type Description
object object A JSON serializable object that may contain FormData instances.

Returns: string — A hash.

See

Examples

Ways to import.

import { hashObject } from 'graphql-react';
import hashObject from 'graphql-react/public/hashObject.js';

Ways to require.

const { hashObject } = require('graphql-react');
const hashObject = require('graphql-react/public/hashObject');

function reportCacheErrors

A GraphQL cache event handler that reports fetch, HTTP, parse and GraphQL errors via console.log(). In a browser environment the grouped error details are expandable.

Parameter Type Description
data GraphQL#event:cache GraphQL cache event data.

Examples

Ways to import.

import { reportCacheErrors } from 'graphql-react';
import reportCacheErrors from 'graphql-react/public/reportCacheErrors.js';

Ways to require.

const { reportCacheErrors } = require('graphql-react');
const reportCacheErrors = require('graphql-react/public/reportCacheErrors');

GraphQL initialized to report cache errors.

import { GraphQL, reportCacheErrors } from 'graphql-react';

const graphql = new GraphQL();
graphql.on('cache', reportCacheErrors);

function useGraphQL

A React hook to manage a GraphQL operation in a component.

Parameter Type Description
options object Options.
options.operation GraphQLOperation GraphQL operation. To reduce work for following renders, define it outside the component or memoize it using the React.useMemo hook.
options.fetchOptionsOverride GraphQLFetchOptionsOverride? Overrides default fetch options for the GraphQL operation. To reduce work for following renders, define it outside the component or memoize it using the React.useMemo hook.
options.cacheKeyCreator GraphQLCacheKeyCreator? = hashObject GraphQL cache key creator for the operation.
options.loadOnMount boolean? = false Should the operation load when the component mounts.
options.loadOnReload boolean? = false Should the operation load when the GraphQL reload event fires and there is a GraphQL cache value to reload, but only if the operation was not the one that caused the reload.
options.loadOnReset boolean? = false Should the operation load when the GraphQL reset event fires and the GraphQL cache value is deleted, but only if the operation was not the one that caused the reset.
options.reloadOnLoad boolean? = false Should a GraphQL reload happen after the operation loads, excluding the loaded operation cache.
options.resetOnLoad boolean? = false Should a GraphQL reset happen after the operation loads, excluding the loaded operation cache.

Returns: GraphQLOperationStatus — GraphQL operation status.

See

Examples

Ways to import.

import { useGraphQL } from 'graphql-react';
import useGraphQL from 'graphql-react/public/useGraphQL.js';

Ways to require.

const { useGraphQL } = require('graphql-react');
const useGraphQL = require('graphql-react/public/useGraphQL');

Options guide for common situations.

Situation loadOnMount loadOnReload loadOnReset reloadOnLoad resetOnLoad
Profile query ✔️ ✔️ ✔️
Login mutation ✔️
Logout mutation ✔️
Change password mutation
Change name mutation ✔️
Like a post mutation ✔️

constant GraphQLContext

React context object for a GraphQL instance.

Type: object

Property Type Description
Provider Function React context provider component.
Consumer Function React context consumer component.

See

Examples

Ways to import.

import { GraphQLContext } from 'graphql-react';
import GraphQLContext from 'graphql-react/public/GraphQLContext.js';

Ways to require.

const { GraphQLContext } = require('graphql-react');
const GraphQLContext = require('graphql-react/public/GraphQLContext');

A button component that resets the GraphQL cache.

import { GraphQLContext } from 'graphql-react';
import React from 'react';

const ResetCacheButton = () => {
  const graphql = React.useContext(GraphQLContext);
  return <button onClick={graphql.reset}>Reset cache</button>;
};

type GraphQLCache

A GraphQL cache map of GraphQL operation results.

Type: object<GraphQLCacheKeyGraphQLCacheValue>

See

  • GraphQL constructor accepts this type for options.cache.
  • GraphQL instance property cache is this type.

type GraphQLCacheKey

A GraphQL cache key to identify a GraphQL cache value. Typically created by a GraphQL cache key creator that hashes the fetch options of the associated GraphQL operation using hashObject.

Type: string


type GraphQLCacheKeyCreator

GraphQL cache key creator for a GraphQL operation. It can either use the provided fetch options (e.g. derive a hash), or simply return a hardcoded string.

Type: Function

Parameter Type Description
options GraphQLFetchOptions GraphQL fetch options tailored to the GraphQL operation, e.g. if there are files to upload options.body will be a FormData instance conforming to the GraphQL multipart request spec.

See

  • GraphQL instance method operate accepts this type for options.cacheKeyCreator.
  • useGraphQL React hook accepts this type for options.cacheKeyCreator.

type GraphQLCacheValue

JSON serializable GraphQL operation result that includes errors and data.

Type: object

Property Type Description
fetchError string? fetch error message.
httpError HttpError? fetch Response HTTP error.
parseError string? Parse error message.
graphQLErrors Array? GraphQL response errors.
data object? GraphQL response data.

type GraphQLFetchOptions

GraphQL API URL and polyfillable fetch options. The url property gets extracted and the rest are used as fetch options.

Type: object

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

See


type GraphQLFetchOptionsOverride

Overrides default GraphQL fetch options. Mutate the provided options object; there is no need to return it.

Type: Function

Parameter Type Description
options GraphQLFetchOptions GraphQL fetch options tailored to the GraphQL operation, e.g. if there are files to upload options.body will be a FormData instance conforming to the GraphQL multipart request spec.

See

  • GraphQL instance method operate accepts this type for options.fetchOptionsOverride.
  • useGraphQL React hook accepts this type for options.fetchOptionsOverride.

Examples

Setting GraphQL fetch options for an imaginary 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/mutations.
variables object Variables used in the query.

See

  • GraphQL instance method operate accepts this type for options.operation.
  • useGraphQL React hook accepts this type for options.operation.

type GraphQLOperationLoading

A loading GraphQL operation.

Type: object

Property Type Description
cacheKey GraphQLCacheKey GraphQL cache key.
cacheValue GraphQLCacheValue? GraphQL cache value from the last identical query.
cacheValuePromise Promise<GraphQLCacheValue> Resolves the loaded GraphQL cache value.

See


type GraphQLOperationStatus

The status of a GraphQL operation managed by the useGraphQL React hook.

Type: object

Property Type Description
load Function Loads the current GraphQL operation on demand, updating the GraphQL cache.
loading boolean Is the current GraphQL operation loading.
cacheKey GraphQLCacheKey GraphQL cache key for the current GraphQL operation and GraphQL fetch options.
cacheValue GraphQLCacheValue GraphQL cache value for the current GraphQL cache key.
loadedCacheValue GraphQLCacheValue GraphQL cache value that was last loaded by this useGraphQL React hook; even if the GraphQL cache key has since changed.

See


type HttpError

fetch HTTP error.

Type: object

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

type ReactNode

A React virtual DOM node; anything that can be rendered.

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].