Vue Apollo“ __ typename”在updateQuery中未定义

时间:2020-08-06 18:36:22

标签: vue.js graphql strapi vue-apollo

我正在尝试为我的帖子索引创建一个“显示更多”按钮。索引查询在前5个帖子中加载正常,当我单击“显示更多”按钮时,我可以看到返回了新帖子,但是我收到一堆错误,例如:

Missing field id in {
  "__typename": "Post",
  "posts": [
    {
      "id": "5f2b26600c3ec47b279d8988",
      "title": 

对于每个帖子属性(id,标题,内容,内容等等),我几乎都会收到其中一种错误。这样可以防止将实际的新帖子添加到索引中。是什么导致此问题?

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

1 个答案:

答案 0 :(得分:2)

我认为问题出在这里

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