数据未合并,Apollo 3分页与现场策略

如何解决数据未合并,Apollo 3分页与现场策略

这是我的两个文件。我试图用我自己的数据模拟此沙盒的结果:https://codesandbox.io/embed/stoic-haze-ispw2?codemirror=1

基本上,我可以看到数据已被获取并且缓存已更新,但是我的组件ResourceSection数据列表未更新。

[UPDATE]根据反馈进行了一些重大更改。从组件中删除了查询,我做了一个skipLimitPagination函数。该查询有效,但是我的缓存未更新或将数据放入其中。

import React from "react";
import { BrowserRouter as Router } from "react-router-dom";
import "./App.css";
import { ApolloClient,InMemoryCache,ApolloProvider } from "@apollo/client";
import Home from "./screens";
import { skipLimitPagination } from './utils/utilities'

const client = new ApolloClient({
  uri: `https://graphql.contentful.com/content/v1/spaces/${process.env.REACT_APP_SPACE_ID}/?access_token=${process.env.REACT_APP_CDA_TOKEN}`,cache: new InMemoryCache({
   typePolicies: {
     Query: {
       fields: {
         resourceCollection: {items: skipLimitPagination()}
       }
     }
   }
  }),});

function App() {
  return (
    <ApolloProvider client={client}>
      <Router>
        <Home />
      </Router>
    </ApolloProvider>
  );
}

export default App;
import React,{ useState } from "react";
import Navbar from "../components/Navbar";
import MobileNav from "../components/MobileNav";
import HeroSection from "../components/HeroSection";
import FeaturesSection from "../components/FeatureSection";
import Split from "../components/SplitWindow";
import Loading from "../components/Loading";
import { useQuery,gql } from "@apollo/client";
import Resource from "../components/ResourceSection";
import Contact from "../components/ContactSection";
import Footer from "../components/Footer";

const MASS_COLLECTION = gql`
query($skip: Int) {
  resourceCollection(limit: 5,skip: $skip ) {
 items {
   type
   category
   title
   link
   bgColor
   color
 }
},splitSectionCollection(order: splitId_ASC) {
 items {
   splitId
   lightBg
   left
   lightText
   darkText
   image {
     url
   }
   alt
   heading
   content {
     json
   }
 }
} 

}
`;

const Home = () => {
  const [isOpen,setIsOpen] = useState(false);

  const { loading,error,data,fetchMore } = useQuery(MASS_COLLECTION,{
    variables: {
      skip: 0,},});

  if (loading) return <Loading />;
  if (error) return <p>Error</p>;

  const toggle = () => {
    setIsOpen(!isOpen);
  };
  return (
    <>
      <MobileNav isOpen={isOpen} toggle={toggle} />
      <Navbar toggle={toggle} />
      <HeroSection />
      <FeaturesSection />
      {data.splitSectionCollection.items.map((item) => {
        return <Split item={item} key={item.splitId} />;
      })}
      <Resource data={data.resourceCollection.items} fetchMore={fetchMore}/>
      <Contact />
      <Footer />
    </>
  );
};

export default Home;

import React,{ useState,useCallback } from "react";
import {
  ResourceContainer,ResourcesWrapper,ResourceRow,TextWrapper,Column1,Heading,Content,Column2,ImgWrap,Img,Form,FormSelect,FormOption,// LinkContainer,// LinkWrapper,// LinkIcon,// LinkTitle,// LoadMore,// ButtonWrapper,} from "./ResourceElements";

const ResourceSection = ({ data,fetchMore }) => {
  console.log(data)

  const handleClick = useCallback(() => {
    fetchMore({
      variables: {
        skip:
          data 
            ? data.length
            : 0,});
  },[fetchMore,data]);

  return (
    <ResourceContainer lightBg={true} id="resource">
      <ResourcesWrapper>
        <ResourceRow left={true}>
          <Column1>
            <TextWrapper>
              <Heading lightText={false}>Resources</Heading>
              <Content darkText={true} className="split_cms">
                Cyber Streets strives in sharing education resources to all.
                Below you can find an exhaustive list of resources covering
                everything from computer programming to enterneurship. "Be
                knowledgeable in your niche,provide some information free of
                charge,and share other trustworthy people's free resources
                whenever possible..." - Heather Hart
              </Content>
            </TextWrapper>
          </Column1>
          <Column2>
            <ImgWrap>
              <Img
                src="/assets/images/Resource.svg"
                alt="Two looking at computer screen svg"
              />
            </ImgWrap>
          </Column2>
        </ResourceRow>
        <Form action="">
          <FormSelect
          // onChange={(e) => {
          //   setCategory(e.target.value);
          //   // setLimit(5);
          // }}
          >
            <FormOption value="">Filter by category</FormOption>
            <FormOption value="MEDIA">Media</FormOption>
            <FormOption value="TEDX">Ted Talks</FormOption>
            <FormOption value="INTERNET SAFETY/AWARENESS">
              Internet safety &amp; awareness
            </FormOption>
            <FormOption value="K-12/COMPUTER SCIENCE">
              k-12 &amp; computer science
            </FormOption>
            <FormOption value="CODING">Programming</FormOption>
            <FormOption value="CYBER/IT OPERATIONS">
              Cyber &and; IT operations
            </FormOption>
            <FormOption value="ROBOTICS">Robotics</FormOption>
            <FormOption value="CLOUD">Cloud</FormOption>
            <FormOption value="SCIENCE">Science</FormOption>
            <FormOption value="PROFESSIONAL DEVELOPMENT">
              Professional Development
            </FormOption>
            <FormOption value="3D PRINTING">3D Printing</FormOption>
            <FormOption value="ART">Art</FormOption>
            <FormOption value="MOOC">Massive Open Online Courses</FormOption>
            <FormOption value="GAMES">Games &amp; Challenges</FormOption>
            <FormOption value="OTHER">Other</FormOption>
          </FormSelect>
        </Form>
        <div className="list">
          {data.map((resource,i) => (
            <div key={resource.title} className="item">
              {resource.title}
            </div>
          ))}
        </div>

        <button className="button" onClick={handleClick}>
          Fetch!
        </button>
      </ResourcesWrapper>
    </ResourceContainer>
  );
};

export default ResourceSection;

点击获取更多按钮后,我的缓存。两个单独的资源集合,应该合并吗?我通过阿波罗Chrome插件获得了此信息。

我正在使用连续性graphql API:

这是我的资源收集参数和字段:

ResourceCollection
ARGS
skip: Int = 0
limit: Int = 100
preview: Boolean
locale: String
where: ResourceFilter
order: [ResourceOrder]

Fields
total: Int!
skip: Int!
limit: Int!
items: [Resource]!
export function skipLimitPagination(keyArgs) {
    return {
      keyArgs,merge(existing,incoming,{ args }) {
        const merged = existing ? existing.slice(0) : [];
        if (args) {
          const { skip = 0 } = args;
          for (let i = 0; i < incoming.length; ++i) {
            merged[skip + i] = incoming[i];
          }
        } else {
  
          merged.push.apply(merged,incoming);
        }
        return merged;
      },};
  }

我已经连续三天研究这个问题。我尝试了使用更新查询的旧方法,但是它没有按预期工作,所以现在我尝试使用最新的阿波罗技术。请帮助:(

解决方法

我遇到了几乎相同的问题并找到了解决方案。问题在于 Apollo 站点上的所有示例都假定响应对象的第一个元素是您的项目数组。

这不是 Contentful 的工作方式,数组总是嵌套在集合内的 items 中。例如,您的 resourceCollection 有一个属性 items,其中包含您的所有资源。所以你必须合并 items 但返回整个 resourceCollection,它看起来像这样:

new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        resourceCollection: {
          keyArgs: false,merge(existing,incoming) {
            if (!incoming) return existing
            if (!existing) return incoming // existing will be empty the first time 

            const { items,...rest } = incoming;

            let result = rest;
            result.items = [...existing.items,...items]; // Merge existing items with the items from incoming
 
            return result
          }
        }
      }
    }
  }
})

这将返回带有合并的 resourceCollectionitems

,

根查询的类型仅为Query,而不是RootQuery,这就是为什么您对RootQuery.resourceCollection字段的配置没有任何作用的原因。

换句话说,试试这个:

new InMemoryCache({
  typePolicies: {
    Query: { // not RootQuery
      fields: {
        resourceCollection: offsetLimitPagination(),},})

我还建议您在组件外部创建RESOURCE_COLLECTION查询,这样就不必在每次渲染组件时都创建新的DocumentNode

,

我使用@Lingertje 的答案有一段时间了,但一直遇到重复问题,尤其是当我的组件由于用户在没有重新渲染应用程序的情况下浏览和返回而重新渲染时。

查看 Apollo 客户端文档中的 merging arrays of non-normalised objects

您需要为 ResourceCollection 类型的 items 字段设置字段策略,如下所示(示例底部):

import { InMemoryCache } from '@apollo/client'

const mergeItemsById = (existing: any[],incoming: any[],{ readField,mergeObjects }) => {
  const merged: any[] = existing ? existing.slice(0) : [];
  const itemIdToIndex: Record<string,number> = Object.create(null);
  if (existing) {
    existing.forEach((item,index) => {
      itemIdToIndex[readField("id",item)] = index;
    });
  }
  incoming.forEach(item => {
    const id = readField("id",item);
    const index = itemIdToIndex[id];
    if (typeof index === "number") {
      // Merge the new item data with the existing item data.
      merged[index] = mergeObjects(merged[index],item);
    } else {
      // First time we've seen this item in this array.
      itemIdToIndex[id] = merged.length;
      merged.push(item);
    }
  });
  return merged;
}

export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        resourceCollection: {
          keyArgs: ['preview','locale','where','order'],ResourceCollection: {
      fields: {
        items: {
          merge: mergeItemsById
        }
      }
    }
  },})

如果您在 items 上的唯一键不是 id,则将“id”的三个引用更改为您的唯一键。

然后只需在您设置客户端的位置导入此缓存定义(当它变得如此大时,它比内联要简单得多):

const client = new ApolloClient({
  uri: `https://graphql.contentful.com/content/v1/spaces/${process.env.REACT_APP_SPACE_ID}/?access_token=${process.env.REACT_APP_CDA_TOKEN}`,cache: ### import the cache object here ###
});

奖励:请参阅我在 Query 类型的 resourceCollection 字段上设置了 keyArgs,以确保您在更改这些参数时不会重用缓存的结果。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res