javascript - 如何从 NextJS 服务器水合 Apollo 客户端

标签 javascript reactjs apollo react-apollo next.js

我正在使用带有 Apollo 客户端的自定义 NextJS 服务器。我想在服务器端获取 GraphQL 数据,然后将其发送到客户端。我本来可以做到这一点,但客户端再次获取它。据我所知,Apollo 缓存仅在服务器上可用,然后需要发送到客户端并从那里恢复。

Apollo docs提到SSR,但我不想使用Apollo客户端完全渲染我的应用程序,我想使用NextJS,我只想从Apollo客户端获取数据并将其手动注入(inject)HTML以在客户端上恢复它。我查看了一些使用 Apollo 的 NextJS 示例,但没有一个示例展示了如何准确地做到这一点。

这是我的自定义请求处理程序:

const app = next({ dev: process.env.NODE_ENV !== 'production' });

const customHandler = async (req, res) => {
  const rendered = await app.renderToHTML(req, res, req.path, req.query);
  // somehow get the data from the apollo cache and inject it in the rendered html
  res.send(rendered);
}

最佳答案

当您在服务器中创建ApolloClient时,您可以传递initialState来水合缓存。

const createApolloClient = ({ initialState, headers }) =>
    new ApolloClient({
      uri: GRAPHQL_URL,
      cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
    });

export default withApollo(PageComponent, { ssr = true } = {}) => {

  const WithApollo = ({ apolloClient, apolloState, ...pageProps }) => {
    const client = apolloClient || createApolloClient({ initialState: apolloState, headers: {} });

     ... rest of your code. 
  });
});

我专门为此创建了一个名为 nextjs-with-apollo 的包。看看https://github.com/adikari/nextjs-with-apollo 。安装该软件包后,创建一个 HOC。

// hocs/withApollo.js
import withApollo from 'nextjs-with-apollo';
import ApolloClient from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const GRAPHQL_URL = 'https://your-graphql-url';

const createApolloClient = ({ initialState, headers }) =>
    new ApolloClient({
      uri: GRAPHQL_URL,
      cache: new InMemoryCache().restore(initialState || {}) // hydrate cache
    });

export default withApollo(createApolloClient);

然后您就可以在下一个页面中使用该临时内容。

import React from 'react';
import { useQuery } from '@apollo/react-hooks';

import withApollo from 'hocs/withApollo';

const QUERY = gql`
  query Profile {
    profile {
      name
      displayname
    }
  }
`;

const ProfilePage = () => {
  const { loading, error, data } = useQuery(PROFILE_QUERY);

  if (loading) {
    return <p>loading..</p>;
  }

  if (error) {
    return JSON.stringify(error);
  }

  return (
    <>
      <p>user name: {data.profile.displayname}</p>
      <p>name: {data.profile.name}</p>
    </>
  );
};

export default withApollo(ProfilePage);

关于javascript - 如何从 NextJS 服务器水合 Apollo 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867857/

相关文章:

javascript - 如何使用 JavaScript 将选择范围扩展到字边界,仅一次?

javascript - 使用 ramda.js 将对象数组转换为一个对象

javascript - 已内存组件的子组件是否也已内存?

javascript - 谷歌地图 react -Javascript : How to click on a customized marker

reactjs - 使用 React 进行 GraphQL 查询时,JSON 意外结束,而 GraphQL 则没有问题

javascript - 如果用户单击另一个选项,如何使值自动更新?

javascript - 如何修复我的 React 上下文以呈现 useEffect 并重新加载表数据

javascript - componentDidMount 或 componentWillMount 我需要使用哪一个

apollo - 如何告诉 apollo codegen 为查询查找确切的文件

vue.js - 如何为 Vue Apollo 导入 Apollo Client 3?