微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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 举报,一经查实,本站将立刻删除。