Socket
Book a DemoInstallSign in
Socket

next-apollo-hook

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-apollo-hook

Simple Apollo HOC for Next.js (hook supported)

1.0.0
latest
Source
npmnpm
Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

next-apollo-hook

This is a simple Apollo HOC for Next.js. Inspired by next-with-apollo and add hook support from React-Apollo with hook

How to use

Install the package with npm

npm install next-apollo-hook

or with yarn

yarn add next-apollo-hook

Note: apollo-boost is used in this example because is the fastest way to create an ApolloClient, but is not required.

Create the HOC using a basic setup and apollo-boost:

// lib/withApollo.js
import withApollo from 'next-apollo-hook';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { GRAPHQL_URL } from '../configs';

export default withApollo(
  ({ ctx, headers, initialState }) =>
    new ApolloClient({
      uri: GRAPHQL_URL,
      cache: new InMemoryCache().restore(initialState || {})
    })
);

withApollo accepts a function that receives { ctx, headers } in the first render with SSR (Server Side Rendering). This is done to fetch your queries and hydrate the store before we send the page to the browser.

withApollo will receive { initialState } if the render is happening in the browser, with the following line we're hydrating our cache with the initial state created in the server:

cache: new InMemoryCache().restore(initialState || {});

Now let's wrap Next's App in pages/_app.js:

import React from 'react';
import App from 'next/app';
import { ApolloProvider } from '@apollo/react-hooks';
import withApollo from '../lib/withApollo';

class MyApp extends App {
  render() {
    const { Component, pageProps, apolloClient } = this.props;

    return (
      <ApolloProvider client={apolloClient}>
        <Component {...pageProps} />
      </ApolloProvider>
    );
  }
}

export default withApollo(MyApp);

Now every page in pages/ can use anything from react-apollo. Pages can access to the ApolloClient too:

Page.getInitialProps = ctx => {
  const apolloClient = ctx.apolloClient;
};

FAQs

Package last updated on 27 Aug 2019

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

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.