question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to use apollo graphql client with universal router to render isomorphically

See original GitHub issue

I’m trying to use the Apollo client and I am running into a few issues with dropping it into the react starter kit with redux. https://github.com/kriasoft/react-starter-kit/tree/feature/redux

Trying to use the techniques from here: http://dev.apollodata.com/react/server-side-rendering.html

But I get the error

warning.js:36Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
 (client) </div></header><div data-reactid="19">Lo
 (server) </div></header><div class="Home-root-2IM

Here’s my implementation

// server.js
...
const component = (
  <App context={context}>
    <ApolloProvider client={context.client} store={context.store}>
      {route.component}
    </ApolloProvider>
  </App>
);


await getDataFromTree(component);

data.children = ReactDOM.renderToString(component);
data.style = [...css].join('');
data.scripts = [
  assets.vendor.js,
  assets.client.js,
];
data.state = context.store.getState();
if (assets[route.chunk]) {
  data.scripts.push(assets[route.chunk].js);
}

const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(route.status || 200);
res.send(`<!doctype html>${html}`);
...

And client side

// client.js
...
const component = (
  <App context={context}>
    <ApolloProvider client={context.client} store={context.store}>
      {route.component}
    </ApolloProvider>
  </App>
);

appInstance = ReactDOM.render(
 component,
  container,
  () => onRenderComplete(route, location),
);
...


// Home.js

class Home extends React.Component {
  static propTypes = {
    collections: PropTypes.arrayOf(PropTypes.shape({
      id: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      subtitle: PropTypes.string.isRequired,
      photo: PropTypes.string,
    })).isRequired,
  };

  render() {
    const props = this.props;
    const { loading, allCollections } = props.data;

    if (loading) {
      return <div>Loading</div>;
    } else {
      return (
        <div className={s.root}>
          <div className={s.container}>
            <h1 className={s.title}>Collections</h1>
            <ul>
              {allCollections.map((collection) =>
                <li key={collection.id}>
                  <h3>{collection.title}</h3>
                  <img src={collection.photo} width="200"/>
                </li>
              )}
            </ul>
          </div>
        </div>
      );
    }

  }
}

Home.propTypes = {
  data: PropTypes.shape({
    loading: PropTypes.bool.isRequired,
    allCollections: PropTypes.array,
  }).isRequired,
};


const HomeWithStyles =  withStyles(s)(Home);
const HomeWithData = graphql(getQuery)(HomeWithStyles);
export default connect()(HomeWithData);

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:17 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
myparkcommented, Mar 1, 2017

@visualskyrim you’ll need to set the client in the context object in server.js with your apollo client, e.g. (note that I’m also using my own redux store as well).

 const client = new ApolloClient({
      ssrMode: true,
      networkInterface: createNetworkInterface(apolloOptions),
    });

 const context = {
      // Enables critical path CSS rendering
      // https://github.com/kriasoft/isomorphic-style-loader
      insertCss: (...styles) => {
        // eslint-disable-next-line no-underscore-dangle
        styles.forEach(style => css.add(style._getCss()));
      },
      // Initialize a new Redux store
      // http://redux.js.org/docs/basics/UsageWithReact.html
      store,
      client,
  };

There is no apollo reducer since that’s handled by apollo itself.

0reactions
ulanicommented, May 27, 2021

@mypark thank you very much for crating this issue! Unfortunately, we have close it due to inactivity. Feel free to re-open it or join our Discord channel for discussion.

NOTE: The main branch has been updated with React Starter Kit v2, using JAM-style architecture.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Server-side rendering - Apollo GraphQL Docs
You need to use a server-compatible router for React, such as React Router. ... In this case, Apollo Client doesn't need to make...
Read more >
What's Next.js for Apollo - Apollo GraphQL Blog
Thanks to GraphQL and a technique known as universal rendering (also known as isomorphic rendering), I've completely changed the way I interact ...
Read more >
Introduction to Apollo Client - Apollo GraphQL Docs
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Use...
Read more >
Integrating with Meteor - Apollo GraphQL Docs
Or if you're using apollo-client instead of apollo-boost , use ... apollo-client redux react-apollo react-router react-helmet express isomorphic-fetch.
Read more >
universal-react-apollo - npm
Lightweight wrapper library around react-apollo and apollo-server-express to build universal (isomorphic) app with less boilerplate.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found