next-apollo-hook

1.0.0 • Public • Published

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

Readme

Keywords

none

Package Sidebar

Install

npm i next-apollo-hook

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

14.3 kB

Total Files

6

Last publish

Collaborators

  • huongdevvn