vue.js - Vue Apollo“__typename”在 updateQuery 中未定义
问题描述
我正在尝试为我的帖子索引创建一个“显示更多”按钮。前 5 个帖子的索引查询加载良好,当我单击“显示更多”按钮时,我可以看到返回的新帖子,但是我收到了一堆错误,例如:
Missing field id in {
"__typename": "Post",
"posts": [
{
"id": "5f2b26600c3ec47b279d8988",
"title":
对于每个帖子属性(id、title、content、slug 等),我几乎都会收到其中一个错误。这可以防止将实际的新帖子添加到索引中。是什么导致了这个问题?
<script>
import postsQuery from '~/apollo/queries/blog/posts';
const pageSize = 5;
export default {
name: 'BlogIndex',
data: () => ({
loadingMorePosts: false,
page: 0,
pageSize,
}),
apollo: {
postsCount: {
prefetch: true,
query: postsQuery,
variables: {
page: 0,
pageSize,
}
},
posts: {
prefetch: true,
query: postsQuery,
variables: {
page: 0,
pageSize,
}
},
},
computed: {
morePosts() {
return this.posts.length < this.postsCount.aggregate.totalCount;
}
},
methods: {
async fetchMorePosts() {
this.page += this.pageSize;
this.$apollo.queries.posts.fetchMore({
variables: {
page: this.page,
pageSize,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
const newPosts = fetchMoreResult.posts;
console.log('typename: ', previousResult.posts.__typename); <--- returns undefined
if (!newPosts.length) return previousResult;
return {
posts: {
__typename: previousResult.posts.__typename,
posts: [...previousResult.posts, ...newPosts],
}
}
}
})
},
},
}
</script>
更新:添加了导入的帖子查询
query Posts($page: Int!, $pageSize: Int!) {
posts(
start: $page
limit: $pageSize
sort: "published_at:desc"
where: { published: true }
) {
id
title
content
slug
published
createdAt
updatedAt
published_at
}
postsCount: postsConnection(where: { published: true }) {
aggregate {
totalCount
}
}
}
解决方案
我认为问题出在这里:
return {
posts: {
__typename: previousResult.posts.__typename,
posts: [...previousResult.posts, ...newPosts],
}
}
我很确定__typename
应该属于每个帖子对象,而不是帖子集合的一部分。让我知道如果这样的事情可以解决它:
return {
posts: {
posts: [...previousResult.posts, ...newPosts]
}
}
并将查询更改为:
query Posts($page: Int!, $pageSize: Int!) {
posts(
start: $page
limit: $pageSize
sort: "published_at:desc"
where: { published: true }
) {
__typename // add this here
id
title
content
slug
published
createdAt
updatedAt
published_at
}
postsCount: postsConnection(where: { published: true }) {
aggregate {
totalCount
}
}
}
推荐阅读
- angular - Angular 在其他组件中获取可观察值
- c# - 计时器事件显示的表单无法正确呈现
- javascript - 然后在构造函数中使用这个集合
- javascript - React 中的 HTML 复选框
- javascript - Chrome 中未获取变量的值
- reactjs - 连接两个看起来相同的枚举的更好方法
- python - “write_timeout”在 pyserial 中的 Serial() 中不起作用
- php - 从数组对象(php)中获取特定数据
- html - 当内容溢出浏览器窗口时,用 div 替换 html 表格布局
- javascript - 将 CSS 类添加到 Vue 禁用的按钮