如何解决数据未合并,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 & awareness
</FormOption>
<FormOption value="K-12/COMPUTER SCIENCE">
k-12 & computer science
</FormOption>
<FormOption value="CODING">Programming</FormOption>
<FormOption value="CYBER/IT OPERATIONS">
Cyber ∧ 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 & 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
}
}
}
}
}
})
这将返回带有合并的 resourceCollection
的 items
。
根查询的类型仅为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 举报,一经查实,本站将立刻删除。