Giter Club home page Giter Club logo

next-apollo's Introduction

Next Apollo Build Status

A package for using Apollo within a Next.js application.

Demo

Installation

This project assumes you have react, react-dom, and next installed. They're specified as peerDependencies.

npm install --save next-apollo graphql @apollo/client

Documentation

Create an Apollo Client, pass it into to the withApollo higher-order component and export the returned component.

import { withApollo } from "next-apollo";
import { ApolloClient, InMemoryCache } from "@apollo/client";

const apolloClient = new ApolloClient({
  uri: "https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn",
  cache: new InMemoryCache(),
});

export default withApollo(apolloClient);

Inside your Next.js page, wrap your component with your exported higher order component.

import withApollo from "../lib/apollo";

const Page = (props) => <div>Hello World</div>;

// Default export is required for Fast Refresh
export default withApollo({ ssr: true })(Page);

That's it!

How Does It Work?

Next-apollo integrates Apollo seamlessly with Next by wrapping our pages inside a higher-order component (HOC). Using a HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application.

On initial page load, while on the server and inside getInitialProps, the Apollo method, getDataFromTree, is invoked and returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized.

License

MIT

next-apollo's People

Contributors

adamsoffer avatar alyavasilyeva avatar arcanis avatar ascott1 avatar bogas04 avatar couturecraigj avatar dependabot[bot] avatar ecklf avatar freeatnet avatar gregorskii avatar guibernardino avatar hilaryous avatar johnson-liang avatar jupl avatar kapoko avatar lukel97 avatar lwachira avatar mrorz avatar qathom avatar razor-x avatar thealjey avatar thecleric avatar tmr08c avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next-apollo's Issues

Direct Cache access

Hey I'm wondering do we still have the capabilities of directly reading/writing to the apollo cache. Since the module gives a HOC, I don't actually know where the apollo instance sits.

Any help is deeply appreciated

getDataFromTree is not a function

Hey there, nice handy lib!

Was trying to running next-apollo-example with modified package.json:

"@apollo/react-common": "0.1.0-beta.9",
"@apollo/react-hooks": "0.1.0-beta.11",
"next-apollo": "^3.0.0",

CSR working, but SSR gives following error:

TypeError: (0 , _reactHooks.getDataFromTree) is not a function
    at _callee$ (/PathTo/next-apollo-example/node_modules/next-apollo/dist/withData.js:91:60)
    at tryCatch (/PathTo/next-apollo-example/node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (/PathTo/next-apollo-example/node_modules/regenerator-runtime/runtime.js:271:22)
    at Generator.prototype.(anonymous function) [as next] (/PathTo/next-apollo-example/node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (/PathTo/next-apollo-example/node_modules/@babel/runtime/helpers/asyncToGenerator.js:3:24)
    at _next (/PathTo/next-apollo-example/node_modules/@babel/runtime/helpers/asyncToGenerator.js:25:9)
    at /PathTo-apollo-example/node_modules/@babel/runtime/helpers/asyncToGenerator.js:32:7
    at new Promise (<anonymous>)
    at Function.<anonymous> (/PathTo/next-apollo-example/node_modules/@babel/runtime/helpers/asyncToGenerator.js:21:12)
    at Function.getInitialProps (/PathTo/next-apollo-example/node_modules/next-apollo/dist/withData.js:135:37)
    at loadGetInitialProps (/PathTo/next-apollo-example/node_modules/next-server/dist/lib/utils.js:50:35)
    at _callee$ (/PathTo/next-apollo-example/.next/server/static/development/pages/_app.js:892:51)
    at tryCatch (/PathTo/next-apollo-example/node_modules/regenerator-runtime/runtime.js:45:40)
    at Generator.invoke [as _invoke] (/PathTo/next-apollo-example/node_modules/regenerator-runtime/runtime.js:271:22)
    at Generator.prototype.(anonymous function) [as next] (/PathTo/next-apollo-example/node_modules/regenerator-runtime/runtime.js:97:21)
    at asyncGeneratorStep (/PathTo/next-apollo-example/.next/server/static/development/pages/_document.js:272:24)

Have done some search, found one potential solution:

-- import { getDataFromTree } from '@apollo/react-hooks' 
++ import { getDataFromTree } from '@apollo/react-ssr' 

apollographql/react-apollo#3251
https://www.npmjs.com/package/@apollo/react-ssr

Error: Could not find "client"

I'm trying to integrate this into a project I'm working on but I keep getting the following error:

Could not find "client" in the context or passed in as an option. Wrap the root component in an , or pass an ApolloClient instance in via options.

I've followed along exactly with the example you built but still get the error. Any idea what might be causing this? Here's some of my code. Apollo looks the exact same as what you have, I have a test page.

import React, { FunctionComponent } from 'react';
import TestComponent from '../components/TestComponent';
import withData from '../Apollo';

export default withData((props: any) => {
  return (
    <TestComponent />
  )
})
import React, { FunctionComponent } from 'react';
import { useQuery } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';

const MY_QUERY = gql`QUERY INSIDE HERE`

const TestComponent: FunctionComponent = () => {
  const { data } = useQuery(MY_QUERY, {
    notifyOnNetworkStatusChange: true,
  });

  if (data) {
    return (
      <div>
        <div>I'll map through data here.</div>
      </div>
    );
  } else {
    return <div>Loading...</div>;
  }
};

export default TestComponent;

Add additional getInitialProps to withData

There doesn't seem to be a way to add anything to the getInitialProps hook when using withData. I'm trying to figure out how to use part of the URL as an ID in my apollo query, but for that to work on the client side it needs to happen within the getInitialProps page hook, which is concealed by the withData HOC. Unless I am mistaken?

next-apollo not forwarding static properties on components it wraps

If I'm not wrong, it's currently not possible to work with nested layouts in next-apollo because it doesn't forward the Layout property in an example like

const GroupMembersPage = GroupMembers;

GroupMembersPage.Layout = GroupLayout;

export default withApollo({ ssr: true })(GroupMembersPage);

to the _app page which is quite limiting. If this is something you are interested in supporting (and I don't see why not) I'm happy to open a PR for it

Exact versions in package.json causing duplicate react installs?

I have two versions of React on my page, breaking context. One of them seems to be coming from this library:

/app # cat node_modules/next-apollo/node_modules/react/package.json | grep version
    "type": "version",
  "version": "16.8.2"

I suspect, but don't know for sure, that it's happening because my locally installed version for Next.js 16.8.4 doesn't satisfy the exact dep in this package: https://github.com/adamsoffer/next-apollo/blob/master/package.json#L60

It looks like the semver for this type of package should specify >= instead of exact?

question: server rendering for seo

Hey @adamsoffer,

Thanks for this great package, however got a question, what about server side rendering as you actually don't run get inital props when using the gql tags and useQuery hooks for data fetching.

How is this handled from SSR? because if I refresh the page it's still loading on page load and there is delay, no instant showing of the data.

Dependency on next-server

I'm not fully up to speed on the guts of next, but I'm using a custom express server with my next app. Installing next-server just to get execOnce seems like a lot? Context: I (apparently ) don't have next-server installed locally so when I changed next to a peerdependency in my fork of this project, and installed my fork locally, it didn't work.

Duplicate GraphQL queries

Hi there - new to nextjs + Apollo, so apologies in advance if there is an obvious reason/solution to this. Following the example from the README, my next pages are able to query/mutate data using GraphQL but I noticed the server seems to be making a query while compiling, then the client also makes the same query. It's not necessarily an issue for read-only operations, but some mutations aren't idempotent so the second call from the browser fails.

Is this the expected behavior? Is there a way to have the query execute in either the server or the browser for a given page, but not both? If not, is the only solution to make mutations idempotent so both requests will succeed?

Thanks in advance for any tips/pointers!

Using this with getInitialProps() in pages

The examples I've seen that use this library avoid using getInitialProps() in the page components, whereas the learnnextjs.com prefers doing that and then passing data into child components.

Is the recommendation to always use apollo in components and not pages? How does one use withData and graphql together?

Server side authentication with cookies

I store an authentication token (JWT) in a cookie. I'm trying to access this server side by creating an AuthLink that I compose with HttpLink, which is then passed to the withData HOC. The problem is that in my AuthLink component, I don't seem to have access to the request so that I can set cookies so that the graphql request made in getDataFromTree is properly authenticated.

I've looked at other approaches that are similar to next-apollo and they all pass in the ctx from getInitialProps into the function that initializes the ApolloClient. For example:

// example `withApollo` HOC that passes `ctx` (albeit indirectly through `getToken`)
// that can be accessed in an AuthLink component to access the request cookies
static async getInitialProps(context) {
      const { Component, router, ctx } = context;
      const apolloClient = await initApollo(
        {},
        {
          getToken: () => nextCookies(ctx).token,
        },
      );

When using the withData HOC, it doesn't appear that the request context is made available to the ApolloClient init function, so I'm unable to access and set the cookies in the server side graphql request:

// withData.js
WithApollo.getInitialProps = async ctx => {
          const { AppTree } = ctx

          let pageProps = {}
          if (PageComponent.getInitialProps) {
            pageProps = await PageComponent.getInitialProps(ctx)
          }

          // Run all GraphQL queries in the component tree
          // and extract the resulting data
          const apolloClient = initApolloClient(apolloConfig, null) // <-- ctx not passed in

I feel like I'm missing something obvious. How do I make an authenticated server side graphql request with next-apollo? Is there a way to get the current request so that I can get the cookies server side?

Is my example correct ?

Hello ! This is how i use next-apollo, wrapping each page with withData Hoc, can you confirm this is the correct way ?

https://github.com/nyl-auster/reactpress-graphql/blob/a5d70ee81760688a3af3c27b854307e28bf2b0a2/pages/post.js

I was expecting to be required to create a _app.js file and wrapping my whole app with something like , which seems to be unnecessary with your Hoc.
js <ApolloProvider client={client}>

Are your passing ApolloProvider to every component implementing withData ?

Usage with static generation

Hi, I recently switched to using next-apollo to simplify SSR for my graphql queries. It works perfectly for my SSR but I lose out on automatic static optimization.

Here's a simplified version of my code:

import { withApollo } from 'next-apollo';

// ...

export const withSsr = withApollo(apolloClient);

// then I use it to wrap my pages

function Home(): JSX.Element {
	// some graphql queries here
	return (
		<>
			<Seo />
			<Navbar />
			<Layout>
				<Heading>Featured</Heading>
			</Layout>
		</>
	);
}

export default withSsr({ ssr: true })(Home);

For this page I know the queries at build time so I was thinking of making use of static generation to evaluate my queries ahead of time.

Is there a simpler way to take advantage of next-apollo during build time for this usecase? Or do you think it would be better to do it manually? Thanks.

Dependencies

  • next 9.4.4
  • apollo-client 2.6.10
  • next-apollo 4.0.1

Expose entirety of req and not just headers

I am trying to do server side rendering support using apollo-link-schema server-side for reasons. To do that I need to build the context which is currently dependent on the req HTTP request object. Unfortunately I am unable to do that with the config function argument as I'm only given headers. The library is much more flexible if more things are exposed like next-redux-wrapper.

I can do a PR if interested.

useSubscription hook not working properly

Hey Adam,

I'm trying to port over the @apollo/react-hooks demo from React to Next.js using your library and came across this..

Here is my CodeSandbox. useQuery and useMutation seem to be working perfectly, but useSubscription will return the value of "data" as undefined (althought "loading" seems to be correct)

Any idea what might be the cause of this?

Eliminating Apollo in the production bundle

This is a request for discussion, not a feature request or a bug.

Side-note: this is a fantastic library for using GraphQL with NextJS. Thanks so much for it.

I'm wondering, when server-rendering a site (or statically exporting it), we don't really need all of the Apollo stuff on the client side. All of the data is prefetched. So this technically means that we don't need Apollo at runtime, only on the server side.

BUT, of course, there are <Query>s all throughout the React app. This means that we can't simply make Apollo a server-only module. This is kind of a bummer since react-apollo and apollo-client are not small.

I was hoping to open up some discussion on how this could be mitigated—namely, I'm thinking I'll try to understand how this library stores the extracted client cache and makes it available to child <Query>s. Maybe it would be possible to use a webpack plugin to swap out react-apollo at build time and replace it with a dumb stubbed out version that expects data to be provided by NextJS?

Why does it have to be a HOC?

Hey,

So i've been working on a project that uses Next.js and Apollo client. We had some issues with page re-renders because the Apollo client was being re-instantiated on route changes.

Wrapping the App in a HOC definitely fixes the problem and I see this pattern being used for this problem everywhere online.
I'm trying to understand why this works and maybe what are the other potential solutions to a problem like this?

Thanks for your work on this package btw.

Cheers
Adam

[Documentation] Query component no longer supported?

@adamsoffer thank you for doing all the work you do on this library!

I had a bit of an issue setting up a new project with next-apollo last night. The most jarring part of it, I suppose, is I had a chance to integrate this library in another project just last month and following the documentation worked like a charm.

I eventually stumbled upon https://github.com/adamsoffer/next-apollo-example and got things to work by looking at its code; however, I still have a couple of questions:

  1. Do I understand correctly that next-apollo no longer supports the Query component as of 3.0?
  2. Did I end up with a correct set of dependencies or should I expect it to bite me at some point?
  3. Is there anything I can do to help improve next-apollo's documentation?

P.S. I documented the struggles here in case anyone faces the same issues in the meantime.

Update implementation to use AppTree

In your next-apollo-example, you mention waiting on a bug fix to be able to use useRouter properly: https://github.com/adamsoffer/next-apollo-example/blob/52317222c6a326568056ffa1ed63793fa423d10d/components/Header/index.js#L7

They have fixed it in vercel/next.js#7732

We need to update next-apollo to use AppTree so that this can be properly supported. Afterwords, next-apollo-example should be updated.

Check out how they updated their example here: vercel/next.js@dc9e270

Ship a changelog?

There isn't a CHANGELOG or any content in the github releases so it's difficult to figure out what actually changed.

Data prefetch when changing pages

Is it possible to pre-fetch the data from the queries before the page does a client side render?
Prefetching seems to work fine for SSR but i if transition to another page the graphql queries run after the next page render.

I noticed this didnt happen with https://github.com/lfades/next-with-apollo
The behaviour there is: click on link, query requested and completes, then the page transitions and the next page is rendered with the data.

Concerns about security with credentials visible on the front end

There is something I don't quite understand, since next.js executes code from both the backend and the frontend, it requires part of the code to be executed from the frontend.

I wonder if the credentials of the GraphQL API endpoint would be accessible from the frontend through the window.__NEXT_DATA__ global variable.

And if it is, how would you recommend to securely authenticate to a graphql server? I'm thinking of using a proxy so that the credentials are server-side.

This may not be a concern for a graphql endpoint that is public, but is definitely a concern as soon as there is authentication, and can be easily overlooked.

Dynamic fetching based on route

How would you handle dynamic fetching based on the url path?

I have a simple use case where /page/item1 is my route, and need to fetch the right item data (change the gql query), but since the query is somehow "pre-written", it doesn't seem like dynamic data are possible. Or did I missed something?

New release: apollo-client v3

Hi @adamsoffer

Thanks for creating next-apollo!
I just opened a pull request to support apollo-client v3.

This allows us to use next-apollowith this new release and avoid this kind of error:

Module not found: Error: Can't resolve '@apollo/react-ssr' in '/Users/ameizoso/Workspaces/Logitech/etail-platform/node_modules/next-apollo/dist'

React Apollo’s SSR utilities (like getDataFromTree, getMarkupFromTree, and renderToStringWithData) are included in the @apollo/client package. Access them via @apollo/client/react/ssr:

Cannot read property 'pathname' of undefined

I can't use this library because of the dependency issues, but when I copied most of the source code into my program, I started getting

Cannot read property 'pathname' of undefined

I believe it's because you need to pass the router object as a prop, and I'm not sure if you need it in context. I'm referring to your line: https://github.com/adamsoffer/next-apollo/blob/master/src/withData.js#L43

VS in https://github.com/zeit/next.js/blob/canary/examples/with-apollo/lib/with-apollo-client.js#L27 they pass it as a prop

How to make getInitialProps() work on Pages

Please is it possible to make getInitialProps() to work with this library? Looks like getInitialProps() is somehow swallowed up by this HOC.

See my sample _app.js below. But getInitialProps() is never called:

class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};
    console.log("IT IS WORKING")
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }
    return { pageProps };
  }

  render() {
    const { Component, pageProps, ctx } = this.props;
    return (
        <Container>
            <Component {...pageProps} />
        </Container>
    );
  }
}

export default withData(MyApp);

Server side graphql requests are stacking up

Hey @adamsoffer I’ve been using this HOC for the past one year (when it was version 2.0.x).

Recently I decided to upgrade it to version 5 and bumped the next.js version also to latest.

But when I deployed this, all my backend servers started crashing due to heavy load. On further investigation and putting some Graphql logs, I found that the requests were stacking up on server side requests.

For example, let’s say I request 1 product for the first time, it'll get that data.

2nd time when I request for another product on server side, it'll get that data + the data for previous one.

When this is repeated for 100 products imagine the number of requests made! 🤯

Any idea as to why this is happening? I’m assuming the client is actually being shared on the server.
D64C7105-75B1-4D46-B666-7FE0823F0D91

Cannot find ctx to use inside headers like I did in older versions

This might be dumb question but in past versions I did something like this where I directly passed ctx object to initApollo - https://github.com/benawad/lireddit/blob/master/web/src/utils/createWithApollo.js

and then do something like this while calling the client -

const createClient = (ctx: NextPageContext) =>
  new ApolloClient({
    uri: "http://localhost:4000/graphql", 
    credentials: "include",
    headers: {
      cookie:
        (typeof window === "undefined"
          ? ctx?.req?.headers.cookie
          : undefined) || "",
    },
    cache: new InMemoryCache({}),
  });

Seeing that in latest version, its already converted into ts and supports context, the previous version isnt working now. Can you sort of give some example on how to do it correctly? No hurries.

I do something like this now -

const apolloClient = new ApolloClient({
  uri: "http://localhost:4000/graphql",
  credentials: "include",
  headers: {
    cookie:
      (typeof window === "undefined"
        ? ctx?.req?.headers.cookie
        : undefined) || "",
  },
  cache: new InMemoryCache({}),
});```

my typescript isnt that strong for please ignore silly stuff

TypeError: Cannot assign to read only property '__esModule' of object '#<Object>' thrown by apollo-boost dependency

Steps to reproduce:

npm install --save next-apollo graphql react-apollo

Wrap any sample page with withData HOC export default withData(Index);

The following error es thrown:

TypeError: Cannot assign to read only property '__esModule' of object '#<Object>'
    at /Users/erikvilla/git/gsw-suites-exchange/frontend/node_modules/apollo-boost/lib/bundle.cjs.js:127:74
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/Users/erikvilla/git/gsw-suites-exchange/frontend/node_modules/apollo-boost/lib/bundle.cjs.js:127:36)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/erikvilla/git/gsw-suites-exchange/frontend/node_modules/next-apollo/dist/initApollo.js:12:20)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)

Updating the apollo-boostversion to0.4.2` using shrinkwrap solves the issue

Fetching data on client side after routing

Hello!
I have a similar problem to this one: #54

Everything works just fine, when open any page at the first time - all requests are done at the server side.
But when trying to navigate from page to page, the requests are done at the client side.

I tried to use requests at the root pages components - same result.
And tried to wrap pages components withApollo - same result.

Some details:

  1. I am using TypeScript with Codegen, so all requests are hooks (useQuery from @apollo/client), like:
const AboutPage = () => {
  const { loading, error, data } = useAboutPageQuery()
  ...
}
  1. Also I wrapped _app.js component with withApollo, because I need one request's data for all pages.

  2. My withApollo.ts:

import { withApollo } from 'next-apollo'
import ApolloClient from 'apollo-boost'

const API_URL = process.env.API_URL || 'http://localhost:1337'

const apolloClient = new ApolloClient({
  uri: `${API_URL}/graphql`,
})

export const withSsrApollo = (PageComponent: any) => {
  // @ts-ignore
  return withApollo(apolloClient)({ ssr: true })(PageComponent)
}

Module not found

Hi Adam,

I am getting this error when i try to just
import { withData } from 'next-apollo'

./node_modules/next-apollo/dist/link.js
Module not found: Can't resolve 'next-server/dist/lib/utils' in '/Users/***/node_modules/next-apollo/dist'

These are my dependencies:

"dependencies": {
    "@apollo/react-hooks": "^3.1.1",
    "@apollo/react-ssr": "^3.1.1",
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.9.2",
    "apollo-boost": "^0.4.4",
    "babel-plugin-import": "^1.9.1",
    "graphql": "^14.5.6",
    "next": "latest",
    "next-apollo": "^3.1.4",
    "null-loader": "2.0.0",
    "react": "^16.7.0",
    "react-dom": "^16.7.0"
  }

Make next-apollo a HOC

Hi,

Nice library 👍 but I think there is room for improvement for api of withData also I don't think I would call it a HOC.
From react documentation page

a higher-order component is a function that takes a component and returns a new component

But you are taking two parameters, config object and component as second parameter.

Why does it matter?

  1. Every HOC out there does configuration like this
import HOCFactory from 'cool-hoc'
const myProjectSpecificHOC = HOCFactory(config)
export default myProjctSpecificHOC(props => ....)

You can take a look at redux-form's reduxForm or react-redux's connect from top of my head. Basically if you need configuration for your HOC you make it HOC factory.

  1. You can't use compose like with every other HOC
import { compose } from 'lodash' // or redux

const CoolComponent = props => ...

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  reduxForm({...}),
  withCurrentRoute,
  withData ??? <==== here is the problem
)(CoolComponent)
  1. In every component where you want to use withData you also need to import its config object instead of configuring it once and exporting it. You could then have import { myProjectSpecificWithData } from './hocs' which is much nicer.

TL;DR;

Instead of withData(config, component) do withData(config)(component)

Cache

I was having issues with SSR until I identified what was causing it by digging through your code. You may want to update the readme to tell people not to initialize the cache on their own if that want the SSR to work.

withApollo: cannot read property 'apollo' of undefined

I try to run a test for an Index page wrapped in withApollo but it produces an empty snapshot.

Repository | Snapshot | Page source code

index.test.tsx

import React from 'react'
import renderer from 'react-test-renderer'
import User from '../pages/user'
import Index from '../pages/index'

it('Random pages renders correctly', () => {
  const tree = renderer.create(<User id="Ivan" />).toJSON()
  expect(tree).toMatchSnapshot()
}) // this test is ok

it('Renders index page with apollo HOC', () => {
  const tree = renderer.create(<Index />).toJSON()
  expect(tree).toMatchSnapshot()
}) // this throws an error

Error stack

$ jest --update-snapshot
 FAIL  __tests__/index.test.tsx (23.757s)  
  ✓ Random pages renders correctly (87ms)  
  ✕ Renders index page with apollo HOC (66ms)

  ● Renders index page with apollo HOC     

    TypeError: Cannot read property 'apollo' of undefined

      10 | 
      11 | it('Renders index page with apollo HOC', () => {
    > 12 |   const tree = renderer.create(<Index />).toJSON()
         |                         ^       
      13 |   expect(tree).toMatchSnapshot()      14 | })
      15 | 

      at new WithData (node_modules/next-apollo/dist/withData.js:147:87)
      at constructClassInstance (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3459:18)
      at updateClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6785:5)
      at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7742:16)
      at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11413:12)
      at workLoop (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11445:24)
      at renderRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11528:7)
      at performWorkOnRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12416:7)
      at performWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12328:7)
      at performSyncWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12302:3)
      at requestWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12171:5)
      at scheduleWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11986:5)
      at scheduleRootUpdate (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12585:3)
      at updateContainerAtExpirationTime (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12613:10)      
      at updateContainer (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12624:10)
      at Object.create (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13057:5)
      at Object.create (__tests__/index.test.tsx:12:25)

  console.error node_modules/prop-types/checkPropTypes.js:20
    Warning: Failed prop type: The prop `serverState` is marked as required in `WithData(Index)`, but its value is `undefined`.  
        in WithData(Index) (at __tests__/index.test.tsx:12)

  console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9215
    The above error occurred in the <WithData(Index)> component:
        in WithData(Index) (at __tests__/index.test.tsx:12)
    
    Consider adding an error boundary to your tree to customize error handling behavior.
    Visit https://fb.me/react-error-boundaries to learn more about error boundaries

How to properly run tests for this HOC? Please describe.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.