Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
graphql-react
Advanced tools
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.
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 API can also be used to custom load, cache and server side render any data, even from non-GraphQL sources.
First, polyfill any required globals (see Requirements) that are missing in your server and client environments.
See the next-graphql-react
setup instructions.
To install with npm, run:
npm install graphql-react
Create a single Cache
instance and use the Provider
component to provide it for your app.
To server side render your app, use the waterfallRender
function from react-waterfall-render
.
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…";
}
Consider polyfilling:
Cache store.
Parameter | Type | Description |
---|---|---|
store | object? = {} | Initial cache store. Useful for hydrating cache data from a server side render prior to the initial client side render. |
How to import.
import Cache from "graphql-react/Cache.mjs";
Construct a new instance.
const cache = new Cache();
Store of cache keys and values.
Type: object
Signals that a cache store entry was deleted. The event name starts with the cache key of the deleted entry, followed by /delete
.
Type: CustomEvent
Signals that a cache store entry will be deleted unless the event is canceled via event.preventDefault()
. The event name starts with the cache key of the entry being pruned, followed by /prune
.
Type: CustomEvent
Signals that a cache store entry was set. The event name starts with the cache key of the set entry, followed by /set
.
Type: CustomEvent
Property | Type | Description |
---|---|---|
detail | object | Event detail. |
detail.cacheValue | CacheValue | Cache value that was set. |
Signals that a cache store entry is now stale (often due to a mutation) and should probably be reloaded. The event name starts with the cache key of the stale entry, followed by /stale
.
Type: CustomEvent
Loading store.
How to import.
import Loading from "graphql-react/Loading.mjs";
Construct a new instance.
const loading = new Loading();
Loading store, keyed by cache key. Multiple loading cache values for the same key are set in the order they started.
Type: object<CacheKey, Set<LoadingCacheValue>>
Signals the end of loading a cache value; either the loading finished and the cache value was set, the loading was aborted, or there was an error. The event name starts with the cache key, followed by /end
.
Type: CustomEvent
Property | Type | Description |
---|---|---|
detail | object | Event detail. |
detail.loadingCacheValue | LoadingCacheValue | Loading cache value that ended. |
Signals the start of loading a cache value. The event name starts with the cache key, followed by /start
.
Type: CustomEvent
Property | Type | Description |
---|---|---|
detail | object | Event detail. |
detail.loadingCacheValue | LoadingCacheValue | Loading cache value that started. |
Controls a loading cache value.
Parameter | Type | Description |
---|---|---|
loading | Loading | Loading to update. |
cache | Cache | Cache to update. |
cacheKey | CacheKey | Cache key. |
loadingResult | Promise<CacheValue> | Resolves the loading result (including any loading errors) to be set as the cache value if loading isn’t aborted. Shouldn’t reject. |
abortController | AbortController | Aborts this loading and skips setting the loading result as the cache value. Has no effect after loading ends. |
How to import.
import LoadingCacheValue from "graphql-react/LoadingCacheValue.mjs";
Aborts this loading and skips setting the loading result as the cache value. Has no effect after loading ends.
Type: AbortController
Resolves the loading result, after the cache value has been set if the loading wasn’t aborted. Shouldn’t reject.
Type: Promise<*>
When this loading started.
Type: HighResTimeStamp
Deletes cache entries. Useful after a user logs out.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKeyMatcher | CacheKeyMatcher? | Matches cache keys to delete. By default all are matched. |
How to import.
import cacheDelete from "graphql-react/cacheDelete.mjs";
Deletes a cache entry.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKey | CacheKey | Cache key. |
How to import.
import cacheEntryDelete from "graphql-react/cacheEntryDelete.mjs";
Prunes a cache entry, if no prune event listener cancels the cache entry deletion via event.preventDefault()
.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKey | CacheKey | Cache key. |
How to import.
import cacheEntryPrune from "graphql-react/cacheEntryPrune.mjs";
Sets a cache entry.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKey | CacheKey | Cache key. |
cacheValue | CacheValue | Cache value. |
How to import.
import cacheEntrySet from "graphql-react/cacheEntrySet.mjs";
Stales a cache entry, signalling it should probably be reloaded.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKey | CacheKey | Cache key. |
How to import.
import cacheEntryStale from "graphql-react/cacheEntryStale.mjs";
Prunes cache entries. Useful after a mutation.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKeyMatcher | CacheKeyMatcher? | Matches cache keys to prune. By default all are matched. |
How to import.
import cachePrune from "graphql-react/cachePrune.mjs";
Stales cache entries. Useful after a mutation.
Parameter | Type | Description |
---|---|---|
cache | Cache | Cache to update. |
cacheKeyMatcher | CacheKeyMatcher? | Matches cache keys to stale. By default all are matched. |
How to import.
import cacheStale from "graphql-react/cacheStale.mjs";
Fetches a GraphQL operation, always resolving a GraphQL result suitable for use as a cache value, even if there are errors. Loading errors are added to the GraphQL result errors
property, and have an extensions
property containing client: true
, along with code
and sometimes error-specific properties:
Error code | Reasons | Error specific properties |
---|---|---|
FETCH_ERROR | Fetch error, e.g. the fetch global isn’t defined, or the network is offline. | fetchErrorMessage (string). |
RESPONSE_HTTP_STATUS | Response HTTP status code is in the error range. | statusCode (number), statusText (string). |
RESPONSE_JSON_PARSE_ERROR | Response JSON parse error. | jsonParseErrorMessage (string). |
RESPONSE_MALFORMED | Response JSON isn’t an object, is missing an errors or data property, the errors property isn’t an array, or the data property isn’t an object or null . |
Parameter | Type | Description |
---|---|---|
fetchUri | string | Fetch URI for the GraphQL API. |
fetchOptions | FetchOptions | Fetch options. |
Returns: Promise<GraphQLResult> — Resolves a result suitable for use as a cache value. Shouldn’t reject.
How to import.
import fetchGraphQL from "graphql-react/fetchGraphQL.mjs";
Creates default fetch
options for a GraphQL operation. If the GraphQL operation contains files to upload, the options will be for a GraphQL multipart request, otherwise they will be for a regular GraphQL POST
request.
This utility exists for user convenience and isn’t used directly by the graphql-react
API. If there is no chance the GraphQL operation contains files, avoid using this utility for a smaller bundle size.
Parameter | Type | Description |
---|---|---|
operation | GraphQLOperation | GraphQL operation. |
Returns: FetchOptions — fetch
options.
How to import.
import fetchOptionsGraphQL from "graphql-react/fetchOptionsGraphQL.mjs";
A React component to provide all the React context required to enable the entire graphql-react
API:
Parameter | Type | Description |
---|---|---|
props | object | Component props. |
props.cache | Cache | Cache instance. |
props.children | ReactNode? | React children. |
Returns: ReactNode — React virtual DOM node.
How to import.
import Provider from "graphql-react/Provider.mjs";
Provide a Cache
instance for an app.
import Cache from "graphql-react/Cache.mjs";
import Provider from "graphql-react/Provider.mjs";
import React from "react";
const cache = new Cache();
const App = ({ children }) => <Provider cache={cache}>{children}</Provider>;
A React hook to create a memoized loader from another, that automatically aborts previous loading that started via this hook when new loading starts via this hook, the hook arguments change, or the component unmounts.
Parameter | Type | Description |
---|---|---|
load | Loader | Memoized function that starts the loading. |
Returns: Loader — Memoized function that starts the loading.
How to import.
import useAutoAbortLoad from "graphql-react/useAutoAbortLoad.mjs";
A React hook to prevent a cache entry from being pruned while the component is mounted and automatically keep it loaded. Previous loading that started via this hook aborts when new loading starts via this hook, the hook arguments change, or the component unmounts.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
load | Loader | Memoized function that starts the loading. |
Returns: Loader — Memoized loader created from the load
argument, that automatically aborts the last loading when the memoized function changes or the component unmounts.
useCacheEntryPrunePrevention
, used by this hook.useAutoAbortLoad
, used by this hook.useLoadOnMount
, used by this hook.useLoadOnStale
, used by this hook.useLoadOnDelete
, used by this hook.useWaterfallLoad
, often used alongside this hook for SSR loading.How to import.
import useAutoLoad from "graphql-react/useAutoLoad.mjs";
A React hook to get the cache context.
Returns: Cache — The cache.
How to import.
import useCache from "graphql-react/useCache.mjs";
A React hook to get a cache value using its cache key.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
Returns: CacheValue — Cache value, if present.
How to import.
import useCacheEntry from "graphql-react/useCacheEntry.mjs";
A React hook to prevent a cache entry from being pruned, by canceling the cache entry deletion for prune events with event.preventDefault()
.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
How to import.
import useCacheEntryPrunePrevention from "graphql-react/useCacheEntryPrunePrevention.mjs";
A React hook to get a function for loading a GraphQL operation.
Returns: LoadGraphQL — Loads a GraphQL operation.
How to import.
import useLoadGraphQL from "graphql-react/useLoadGraphQL.mjs";
A React hook to get the loading context.
Returns: Loading — Loading.
How to import.
import useLoading from "graphql-react/useLoading.mjs";
A React hook to get the loading cache values for a given cache key.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
Returns: Set<LoadingCacheValue> | undefined
— Loading cache values, if present.
How to import.
import useLoadingEntry from "graphql-react/useLoadingEntry.mjs";
A React hook to load a cache entry after it’s deleted, if there isn’t loading for the cache key that started after.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
load | Loader | Memoized function that starts the loading. |
How to import.
import useLoadOnDelete from "graphql-react/useLoadOnDelete.mjs";
A React hook to automatically load a cache entry after the component mounts or the cache context or any of the arguments change, except during the hydration time if the hydration time stamp context is populated and the cache entry is already populated.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
load | Loader | Memoized function that starts the loading. |
How to import.
import useLoadOnMount from "graphql-react/useLoadOnMount.mjs";
A React hook to load a cache entry after becomes stale, if there isn’t loading for the cache key that started after.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
load | Loader | Memoized function that starts the loading. |
How to import.
import useLoadOnStale from "graphql-react/useLoadOnStale.mjs";
A React hook to load a cache entry if the waterfall render context is populated, i.e. when waterfall rendering for either a server side render or to preload components in a browser environment.
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
load | Loader | Memoized function that starts the loading. |
Returns: boolean — Did loading start. If so, it’s efficient for the component to return null
since this render will be discarded anyway for a re-render onces the loading ends.
useAutoLoad
, often used alongside this hook.How to import.
import useWaterfallLoad from "graphql-react/useWaterfallLoad.mjs";
React context for a Cache
instance.
Type: object
Property | Type | Description |
---|---|---|
Provider | Function | React context provider component. |
Consumer | Function | React context consumer component. |
How to import.
import CacheContext from "graphql-react/CacheContext.mjs";
React context for the client side hydration time stamp.
Type: object
Property | Type | Description |
---|---|---|
Provider | Function | React context provider component. |
Consumer | Function | React context consumer component. |
How to import.
import HydrationTimeStampContext from "graphql-react/HydrationTimeStampContext.mjs";
React context for a Loading
instance.
Type: object
Property | Type | Description |
---|---|---|
Provider | Function | React context provider component. |
Consumer | Function | React context consumer component. |
How to import.
import LoadingContext from "graphql-react/LoadingContext.mjs";
Number of milliseconds after the first client render that’s considered the hydration time; during which the useAutoLoad
React hook won’t load if the cache entry is already populated.
Type: number
How to import.
import HYDRATION_TIME_MS from "graphql-react/HYDRATION_TIME_MS.mjs";
A unique key to access a cache value.
Type: string
Matches a cache key against a custom condition.
Type: Function
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key. |
Returns: boolean — Does the cache key match the custom condition.
A cache value. If server side rendering, it should be JSON serializable for client hydration. It should contain information about any errors that occurred during loading so they can be rendered, and if server side rendering, be hydrated on the client.
Type: *
fetch
options, called init
in official specs.
Type: object
fetch
parameters docs.fetch
options. Don’t use other options if fetch
is polyfilled for Node.js or legacy browsers.A GraphQL operation. Additional properties may be used; all are sent to the GraphQL server.
Type: object
Property | Type | Description |
---|---|---|
query | string | GraphQL queries or mutations. |
variables | object? | Variables used in the query . |
A GraphQL result.
Type: object
Property | Type | Description |
---|---|---|
data | object? | GraphQL response data. |
errors | Array<GraphQLResultError>? | GraphQL response errors from the server, along with any loading errors added on the client. |
A GraphQL result error; either created by the GraphQL server, or by whatever loaded the GraphQL on the client (e.g. fetchGraphQL
).
Type: object
Property | Type | Description |
---|---|---|
message | object | Error message. |
locations | Array<{line: number, column: number}>? | GraphQL query locations related to the error. |
path | Array<string>? | GraphQL result data field path related to the error. |
extensions | object? | Custom error data. If the error was created on the client and not the GraphQL server, this property should be present and contain at least client: true , although code and error specific properties may be present. |
Milliseconds since the performance time origin (when the current JavaScript environment started running).
Type: number
Starts loading a cache value.
Type: Function
Returns: LoadingCacheValue — The loading cache value.
Loads a GraphQL operation, using the GraphQL fetcher.
Type: Loader
Parameter | Type | Description |
---|---|---|
cacheKey | CacheKey | Cache key to store the loading result under. |
fetchUri | string | fetch URI. |
fetchOptions | FetchOptions | fetch options. |
Returns: LoadingCacheValue — The loading cache value.
A React virtual DOM node; anything that can be rendered.
Type: undefined
| null
| boolean | number | string | React.Element | Array<ReactNode>
16.0.0
^12.22.0 || ^14.17.0 || >= 16.0.0
.files
and exports
fields../package
from the package exports
field; the full package.json
filename must be used in a require
path./public/
..mjs
files instead of CJS in .js
files, accessible via import
but not require
.React.createElement
instead of the the new React JSX runtime.isobject
dependency.useCacheEntryPrunePrevention
React hook to avoid the React.useCallback
React hook.react
and react-dom
as they’re not proper Node.js ESM.process.env.NODE_ENV
.eslint-plugin-compat
.assertBundleSize
function to assert module bundle size in tests:
singleQuote
to the default, false
.FAQs
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 npm package graphql-react receives a total of 1,669 weekly downloads. As such, graphql-react popularity was classified as popular.
We found that graphql-react demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.