首页 > 解决方案 > 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
    }
  }
}

标签: vue.jsgraphqlstrapivue-apollo

解决方案


我认为问题出在这里:

            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
    }
  }
}

推荐阅读