我正在使用带有 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/