• Stars
    star
    718
  • Rank 63,070 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

graphql-react logo

graphql-react

A GraphQL client for React using modern context and hooks APIs thatโ€™s lightweight (< 4 kB) but powerful; the first Relay and Apollo alternative with server side rendering.

The exports can also be used to custom load, cache and server side render any data, even from non-GraphQL sources.

Installation

Note

For a Next.js project, see the next-graphql-react installation instructions.

For Node.js, to install graphql-react and its react peer dependency with npm, run:

npm install graphql-react react

For Deno and browsers, an example import map (realistically use 4 import maps, with optimal URLs for server vs client and development vs production):

{
  "imports": {
    "extract-files/": "https://unpkg.com/[email protected]/",
    "graphql-react/": "https://unpkg.com/[email protected]/",
    "is-plain-obj": "https://unpkg.com/[email protected]/index.js",
    "is-plain-obj/": "https://unpkg.com/[email protected]/",
    "react": "https://esm.sh/[email protected]",
    "react-waterfall-render/": "https://unpkg.com/[email protected]/"
  }
}

These dependencies might not need to be in the import map, depending on what graphql-react modules the project imports from:

Polyfill any required globals (see Requirements) that are missing in your server and client environments.

Create a single Cache instance and use the component Provider to provide it for your app.

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

Examples

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

import useAutoLoad from "graphql-react/useAutoLoad.mjs";
import useCacheEntry from "graphql-react/useCacheEntry.mjs";
import useLoadGraphQL from "graphql-react/useLoadGraphQL.mjs";
import useWaterfallLoad from "graphql-react/useWaterfallLoad.mjs";
import React from "react";

// 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
        }
      }
    }
  }
`;

export default function GitHubRepoStars({ repoId }) {
  const cacheKey = `GitHubRepoStars-${repoId}`;
  const cacheValue = useCacheEntry(cacheKey);

  // A hook for loading GraphQL is available, but custom hooks for loading non
  // GraphQL (e.g. fetching from a REST API) can be made.
  const loadGraphQL = useLoadGraphQL();

  const load = React.useCallback(
    () =>
      // To be DRY, utilize a custom hook for each API your app loads from, e.g.
      // `useLoadGraphQLGitHub`.
      loadGraphQL(
        cacheKey,
        // Fetch URI.
        "https://api.github.com/graphql",
        // Fetch options.
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
            Authorization: `Bearer ${process.env.GITHUB_ACCESS_TOKEN}`,
          },
          body: JSON.stringify({
            query,
            variables: {
              repoId,
            },
          }),
        }
      ),
    [cacheKey, loadGraphQL, repoId]
  );

  // This hook automatically keeps the cache entry loaded from when the
  // component mounts, reloading it if itโ€™s staled or deleted. It also aborts
  // loading if the arguments change or the component unmounts; very handy for
  // auto-suggest components!
  useAutoLoad(cacheKey, load);

  // Waterfall loading can be used to load data when server side rendering,
  // enabled automagically by `next-graphql-react`. To learn how this works or
  // to set it up for a non-Next.js app, see:
  // https://github.com/jaydenseric/react-waterfall-render
  const isWaterfallLoading = useWaterfallLoad(cacheKey, load);

  // When waterfall loading itโ€™s efficient to skip rendering, as the app will
  // re-render once this step of the waterfall has loaded. If more waterfall
  // loading happens in children, those steps of the waterfall are awaited and
  // the app re-renders again, and so forth until thereโ€™s no more loading for
  // the final server side render.
  return isWaterfallLoading
    ? null
    : cacheValue
    ? cacheValue.errors
      ? // Unlike many other GraphQL libraries, detailed loading errors are
        // cached and can be server side rendered without causing a
        // server/client HTML mismatch error.
        "Error!"
      : cacheValue.data.repo.stargazers.totalCount
    : // In this situation no cache value implies loading. Use the
      // `useLoadingEntry` hook to manage loading in detail.
      "Loadingโ€ฆ";
}

Requirements

Supported runtime environments:

Consider polyfilling:

Non Deno projects must configure TypeScript to use types from the ECMAScript modules that have a // @ts-check comment:

Exports

The npm package graphql-react features optimal JavaScript module design. It doesnโ€™t have a main index module, so use deep imports from the ECMAScript modules that are exported via the package.json field exports:

More Repositories

1

apollo-upload-client

A terminating Apollo Link for Apollo Client that fetches a GraphQL multipart request if the GraphQL variables contain files (by default FileList, File, or Blob instances), or else fetches a regular GraphQL POST or GET request (depending on the config and GraphQL operation).
JavaScript
1,527
star
2

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.
JavaScript
1,427
star
3

graphql-multipart-request-spec

A spec for GraphQL multipart form requests (file uploads).
994
star
4

apollo-upload-examples

A full stack demo of file uploads via GraphQL mutations using Apollo Server and apollo-upload-client.
JavaScript
427
star
5

ruck

Ruck is an open source buildless React web application framework for Deno.
JavaScript
149
star
6

Barebones

A barebones boilerplate for getting started on a bespoke front end.
JavaScript
125
star
7

Fix

A CSS normalization/reset reference.
CSS
123
star
8

next-graphql-react

A graphql-react integration for Next.js.
JavaScript
77
star
9

find-unused-exports

A Node.js CLI and equivalent JS API to find unused ECMAScript module exports in a project.
JavaScript
56
star
10

extract-files

A function to recursively extract files and their object paths within a value, replacing them with null in a deep clone without mutating the original value. FileList instances are treated as File instance arrays. Files are typically File and Blob instances.
JavaScript
54
star
11

coverage-node

A simple CLI to run Node.js and report code coverage.
JavaScript
53
star
12

graphql-api-koa

GraphQL execution and error handling middleware written from scratch for Koa.
JavaScript
52
star
13

svg-symbol-viewer

An online, no-upload drag-and-drop SVG file symbol extractor and viewer.
JavaScript
36
star
14

graphql-react-examples

Deno Ruck web app demonstrating graphql-react functionality using various GraphQL APIs.
JavaScript
36
star
15

Purty-Picker

A super lightweight visual HSL, RGB and hex color picker with a responsive, touch-friendly and customizable UI. Compatible with jQuery or Zepto.
JavaScript
36
star
16

fake-tag

A fake template literal tag to trick syntax highlighters, linters and formatters into action.
JavaScript
33
star
17

next-server-context

A Next.js App or page decorator, React context object, and React hook to access Node.js HTTP server context when rendering components.
JavaScript
31
star
18

jsdoc-md

A Node.js CLI and equivalent JS API to analyze source JSDoc and generate documentation under a given heading in a markdown file (such as readme.md).
JavaScript
26
star
19

next-router-events

A more powerful Next.js router events API.
JavaScript
26
star
20

test-director

An ultra lightweight unit test director for Node.js.
JavaScript
25
star
21

device-agnostic-ui

Device agnostic styles, components & hooks for React apps.
JavaScript
18
star
22

snapshot-assertion

Asserts a string matches a snapshot saved in a file. An environment variable can be used to save rather than assert snapshots.
JavaScript
16
star
23

Focal

Simulates a camera focus within a CSS 3D transform powered scene using CSS blur filters.
JavaScript
12
star
24

scroll-animator

Smart, lightweight functions to animate browser scroll.
JavaScript
12
star
25

graphql-http-test

A JavaScript API and CLI to test a GraphQL server for GraphQL over HTTP spec compliance.
JavaScript
12
star
26

eslint-config-env

ESLint config optimized for authoring packages that adapts to the project environment.
JavaScript
11
star
27

nova-deno

A Nova editor extension that integrates the Deno JavaScript/TypeScript runtime and tools.
JavaScript
9
star
28

webpack-watch-server

A single npm script command to start Webpack and your server in watch mode, with a unified console.
JavaScript
9
star
29

Skid

An ultra-lightweight slider utilizing Hurdler for URL hash based control.
JavaScript
8
star
30

Hurdler

Enables hash links to web page content hidden beneath layers of interaction.
JavaScript
7
star
31

audit-age

A Node.js CLI and equivalent JS API to audit the age of installed production npm packages.
JavaScript
7
star
32

ruck-website

The ruck.tech website for Ruck, an open source buildless React web application framework for Deno.
JavaScript
6
star
33

react-waterfall-render

Renders nested React components with asynchronous cached loading; useful for GraphQL clients and server side rendering.
JavaScript
6
star
34

babel-plugin-syntax-highlight

A Babel plugin that transforms the code contents of template literals lead by comments specifying a Prism.js language into syntax highlighted HTML.
JavaScript
6
star
35

google-static-maps-styler-query

Converts a Google Maps styler array to a Google Static Maps styler URL query string.
JavaScript
5
star
36

constraint-validation-buggyfill

Prevents invalid form submission in browsers that improperly support the HTML forms spec (i.e. Safari).
JavaScript
5
star
37

babel-plugin-transform-runtime-file-extensions

A Babel plugin that adds file extensions to Babel runtime import specifiers and require paths for Node.js ESM compatibility.
JavaScript
4
star
38

eslint-plugin-optimal-modules

An ESLint plugin to enforce optimal JavaScript module design.
JavaScript
4
star
39

install-from

Reliably installs a local package into another, for testing.
JavaScript
4
star
40

babel-plugin-transform-require-extensions

A Babel plugin that transforms specified require path file extensions.
JavaScript
3
star
41

device-agnostic-ui-website

The Device Agnostic UI website.
JavaScript
3
star
42

disposable-directory

Asynchronously creates a disposable directory in the OS temporary directory that gets deleted after the callback is done or errors.
JavaScript
3
star
43

class-name-prop

A lightweight utility function to create a React className prop value for multiple class names.
JavaScript
2
star
44

replace-stack-traces

A JavaScript function to replace error stack traces and following Node.js versions at any indent in a multiline string.
JavaScript
2
star
45

revertable-globals

Sets globals in a JavaScript environment that can be easily reverted to restore the original environment; useful for testing code that relies on the presence of certain globals.
JavaScript
2
star
46

eslint-config-barebones

Barebones ESLint config, extending JavaScript Standard Style.
JavaScript
1
star