首页 > 解决方案 > Apollo GraphQL 反应突变未正确更新 UI

问题描述

我有一个极端情况,其中我的apollo-graphql反应突变没有正确更新 UI,但前提是edges数组最初为空。

我正在尝试向父评论添加新的评论回复,并在进行突变后让新评论出现在列表中。这适用于已经存在至少一个评论回复的情况,但添加第一个评论回复在突变后永远不会更新,除非我刷新页面。

这是变异函数

...

const queryVariables = {
  last: 2,
  parentId: comment.id,
  sortBy: "MODIFIED_AT_ASC",
};

const [createPostComment] = useMutation(CREATE_POST_COMMENT, {
  update(cache, { data: { createComment } }) {
    const { allComments } = cache.readQuery({
      query: GET_COMMENT_CHILDREN,
      variables: queryVariables,
    });

    cache.writeQuery({
      query: GET_COMMENT_CHILDREN,
      variables: queryVariables,
      data: {
        allComments: {
          ...allComments,
          edges: allComments.edges.concat({ // if this is empty, it doesn't update
            node: createComment.comment,
            __typename: "CommentEdge",
          }),
        },
      },
    });
  },
});

createPostComment({
    variables: {
    input: {
      parentId: comment.id,
      userPostId: comment.userPost.id,
      appUserId: 1,
      content: content,
    },
  },
});

...

这里是CREATE_POST_COMMENT突变

import gql from "graphql-tag";

import { CommentFragment } from "gql/fragments";

export const CREATE_POST_COMMENT = gql`
  mutation CreatePostComment($input: CommentInput!) {
    createComment(input: $input) {
      comment {
        ...CommentFragment
        userPost {
          id
        }
        children {
          edges {
            node {
              ...CommentFragment
              userPost {
                id
              }
            }
          }
        }
      }
    }
  }
  ${CommentFragment}
`;

GET_COMMENT_CHILDREN查询

import gql from "graphql-tag";

import { CommentFragment } from "gql/fragments";

export const GET_COMMENT_CHILDREN = gql`
  query allCommentChildren(
    $last: Int!
    $before: String
    $sortBy: [CommentObjectSortEnum]!
    $parentId: Int!
  ) {
    allComments(
      last: $last
      before: $before
      sort: $sortBy
      filters: { parentId: $parentId }
    ) {
      pageInfo {
        startCursor
        hasPreviousPage
      }
      edges {
        node {
          ...CommentFragment
          userPost {
            id
          }
        }
      }
    }
  }
  ${CommentFragment}
`;

评论片段

export const CommentFragment = gql`
  fragment CommentFragment on CommentObject {
    id
    content
    createdAt
    parentId
  }
`;

edges当评论回复已经存在但最初为空时,为什么这可以正常工作?

标签: reactjsgraphqlreact-apolloapollo-clientgraphql-js

解决方案


推荐阅读