1

我正在尝试将 Apollo 客户端状态数据与钩子一起使用,useQuery并将useMutation其用作 NextJS 应用程序中的全局存储。当我按照 NextJS 中的示例with-apollohttps://github.com/zeit/next.js/tree/canary/examples/with-apollo)进行操作时,它使用一个 HOC,在其中运行所有查询并呈现应用程序首先是服务器。

通常,您希望在这样的组件中捕获“加载”状态:

const { loading, data } = useQuery(GET_NAME_QUERY) // some @client query
if (loading) return <p>Loading...</p>
return <h1>Hello {data.name</h1>

但我想跳过加载检查并始终有一个可用的默认状态。我认为这可以通过将 apollo-client 的缓存设置为一组默认值来完成,如下所示:

const cache = new InMemoryCache().restore(initialState);

// This is the part where the initial client-state data is set:
cache.writeData({
  data: { name: 'Harry' } 
});

const apolloClient =  new ApolloClient({
  cache,  // <-- cache with preset client-state data
  typeDefs,
  resolvers,
})

目标是这样做:

const { data } = useQuery(GET_NAME_QUERY) // some @client query, resolves immediately from cache
return <h1>Hello {data.name</h1>

我创建了一个带有机器人的存储库,它的名称和状态从一开始就以这种方式缓存。见https://github.com/rnacken/next-with-apollo-client-state-cache

客户端工作,没有任何错误,但在 SSR 期间,我收到一个错误,因为它在调用后还没有数据(并且“加载”是真的)useQuery。当我记录加载/数据状态时,我在服务器上看到了这个: SSR 错误 在客户端上,一切都很好: 客户

有人知道这是怎么回事吗?使用缓存集,我不应该看到 loading:true 状态,对吧?getDataFromTree从不@apollo/react-ssr正常工作?

4

0 回答 0