npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@shopify/react-graphql-universal-provider

v6.1.2

Published

A self-serializing/deserializing GraphQL provider that works for isomorphic applications

Downloads

21,816

Readme

@shopify/react-graphql-universal-provider

Build Status Build Status License: MIT npm version npm bundle size (minified + gzip)

A self-serializing/deserializing GraphQL provider that works for isomorphic applications.

Installation

yarn add @shopify/react-graphql-universal-provider

Self serializers

A self-serializer is a React component that leverages the useSerialized() hook from @shopify/react-html to handle both serializing data during server rendering, and deserializing it on the client. The components often render React.context() providers to make their serialized state available to the rest of the app they're rendered in.

Comparison with traditional serialization techniques

Consider the I18n self-serializer. In the server you may want to set the locale based on the Accept-Language header. The client needs to be informed of this somehow to make sure React can render consistently. Traditionally you might do something like:

On the server

  • get the locale from the Accept-Language header in your node server
  • create an instance of I18nManager with that locale
  • pass the instance into your app
  • render a <Serialize name="locale" /> component in the DOM you send to the client

On the client

  • call getSerialized('locale') in your client entrypoint for your locale
  • create an instance of I18nManager with that locale
  • pass the instance into your app

In your react app's universal code

  • have your app render an <I18nProvider /> with the manager from props

With self-serializers you would instead:

On the server

  • get the locale from the Accept-Language header in your node server
  • pass the locale into your app directly

On the client

  • render your app without passing in the locale

In your react app's universal code

  • have your app render an <I18n /> with the locale from props

Since self-serializers handle the details of serialization they allow you to remove code from your client/server entrypoints and instead let the react app itself handle those concerns.

Usage

Props

The component takes children and a function that can create an Apollo client. This function will be called when needed, and the resulting Apollo client will be augmented with the serialized initial data.

The Apollo Client by default has the following option values. These values can also be overwritten using the return value of the createClientOptions prop.

const IS_SERVER = typeof window === 'undefined';

const defaultClientOptions = {
  cache: new InMemoryCache()
  ssrMode: IS_SERVER,
  ssrForceFetchDelay: 100,
  connectToDevTools: !IS_SERVER,
};

Basic Example

// App.tsx

import {GraphQL} from '../GraphQL';

export function App({url}: {url: URL}) {
  return <GraphQL url={url}>{/* rest of the app */}</GraphQL>;
}
// GraphQL.tsx
import React from 'react';
import fetch from 'cross-fetch';
import {createHttpLink} from '@apollo/client';
import {GraphQLUniversalProvider} from '@shopify/react-graphql-universal-provider';

export function GraphQL({
  url,
  children,
}: {
  url: URL;
  children?: React.ReactNode;
}) {
  const createClientOptions = () => {
    const link = createHttpLink({
      // make sure to use absolute URL on the server
      uri: `${url.origin}/graphql`,
      fetch,
    });

    return {link};
  };

  return (
    <GraphQLUniversalProvider createClientOptions={createClientOptions}>
      {children}
    </GraphQLUniversalProvider>
  );
}

You’ll know that this library is hooked up properly when the HTML response from server-side rendering:

  • contains a <script type="text/json" data-serialized-id="apollo"></script> element with the contents set to a JSON representation of the contents of the Apollo cache, and
  • does not present the loading state for any GraphQL-connected component that shows data immediately when available (this excludes any queries with a fetchPolicy that ignores the cache).

Using it with cookie

This example will also show getting cookie using @shopify/react-network but this is certainly not an requirement.

// App.tsx
import React from 'react';
import {GraphQL} from '../GraphQL';

export function App({url}: {url: URL}) {
  return <GraphQL url={url}>{/* rest of the app */}</GraphQL>;
}
// GraphQL.tsx
import React from 'react';
import fetch from 'cross-fetch';
import {createHttpLink} from '@apollo/client';
import {useRequestHeader} from '@shopify/react-network';
import {GraphQLUniversalProvider} from '@shopify/react-graphql-universal-provider';

function GraphQL({url, children}: {url: URL; children?: React.ReactNode}) {
  const cookie = useRequestHeader('cookie');

  const createClientOptions = () => {
    const link = createHttpLink({
      // make sure to use absolute URL on the server
      uri: `${url.origin}/graphql`,
      fetch,
      headers: {
        cookie,
      },
    });

    return {link};
  };

  return (
    <GraphQLUniversalProvider createClientOptions={createClientOptions}>
      {children}
    </GraphQLUniversalProvider>
  );
}

Customizing the serialized id

// GraphQL.tsx
import React from 'react';
import fetch from 'cross-fetch';
import {createHttpLink} from '@apollo/client';
import {GraphQLUniversalProvider} from '@shopify/react-graphql-universal-provider';

export function GraphQL({
  url,
  children,
}: {
  url: URL;
  children?: React.ReactNode;
}) {
  const createClientOptions = () => {
    const link = createHttpLink({
      // make sure to use absolute URL on the server
      uri: `${url.origin}/graphql`,
      fetch,
    });

    return {link};
  };

  return (
    <GraphQLUniversalProvider
      id="graphql-cache"
      createClientOptions={createClientOptions}
    >
      {children}
    </GraphQLUniversalProvider>
  );
}