如何在 NextJs 中的页面转换之间使用相同的 Apollo 缓存?

问题描述

我有以下来自 NextJS 官方示例存储库的 apolloClient.js 文件

import { ApolloClient,HttpLink,InMemoryCache } from '@apollo/client'
import { concatPagination } from '@apollo/client/utilities'
import merge from 'deepmerge'
import isEqual from 'lodash/isEqual'
import { useMemo } from 'react'

export const APOLLO_STATE_PROP_NAME = '__APOLLO_STATE__'

let apolloClient

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',link: new HttpLink({
      uri: 'https://nextjs-graphql-with-prisma-simple.vercel.app/api',// Server URL (must be absolute)
      credentials: 'same-origin',// Additional fetch() options like `credentials` or `headers`
    }),cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            allPosts: concatPagination(),},}),})
}

export function initializeApollo(initialState = null) {
  const _apolloClient = apolloClient ?? createApolloClient()

  // If your page has Next.js data fetching methods that use Apollo Client,the initial state
  // gets hydrated here
  if (initialState) {
    // Get existing cache,loaded during client side data fetching
    const existingCache = _apolloClient.extract()

    // Merge the existing cache into data passed from getStaticProps/getServerSideProps
    const data = merge(initialState,existingCache,{
      // combine arrays using object equality (like in sets)
      arrayMerge: (destinationArray,sourceArray) => [
        ...sourceArray,...destinationArray.filter((d) =>
          sourceArray.every((s) => !isEqual(d,s))
        ),],})

    // Restore the cache with the merged data
    _apolloClient.cache.restore(data)
  }
  // For SSG and SSR always create a new Apollo Client
  if (typeof window === 'undefined') return _apolloClient
  // Create the Apollo Client once in the client
  if (!apolloClient) apolloClient = _apolloClient

  return _apolloClient
}

export function addApolloState(client,pageProps) {
  if (pageProps?.props) {
    pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract()
  }

  return pageProps
}

export function useApollo(pageProps) {
  const state = pageProps[APOLLO_STATE_PROP_NAME]
  const store = useMemo(() => initializeApollo(state),[state])
  return store
}

我有两个页面:page1.js,其中我使用了 Apollo 钩子 (useQuery()),第二个页面 page2.js 什么都不做,只返回 null。问题是,如果我使用 Chrome 扩展程序检查 Apollo 缓存,则第 1 页上的查询的缓存结果不会出现在第 2 页上。

如何仅使用 1 个全局缓存并防止在页面转换之间重新初始化缓存?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)