首页 > 解决方案 > 替换 Query 对象的 getPosts 字段时,缓存数据可能会丢失。阿波罗

问题描述

我正在设置我的按钮来点赞帖子。如果不喜欢,则显示基本,喜欢时显示彩色。但是,当单个用户点赞和发布时,他不能不喜欢它,并且点赞数在点赞计数器中不断增加,并且无法返回基本。请帮帮我。单击喜欢的帖子后,如何设置与帖子不同的用户。这是我的代码:

function LikeButton({
  user,
  post: {
    id,
    likeCount,
    likes
  }
}) {
  const [liked, setLiked] = useState(false);

  useEffect(() => {
    if (user && likes.find((like) => like.username === user.username)) {
      setLiked(true);
    } else setLiked(false);
  }, [user, likes]);

  const [likePost] = useMutation(LIKE_POST_MUTATION, {
    variables: {
      postId: id
    }
  });

  const likeButton = user ? (
    liked ? ( <
      Button color = "black" >
      <
      Icon name = "heart" / >
      <
      /Button>
    ) : ( <
      Button color = "black"
      basic >
      <
      Icon name = "heart" / >
      <
      /Button>
    )
  ) : ( <
    Button as = {
      Link
    }
    to = "/login"
    color = "black"
    basic >
    <
    Icon name = "heart" / >
    <
    /Button>
  );

  return ( <
    Button as = 'div'
    labelPosition = 'right'
    onClick = {
      likePost
    } > {
      likeButton
    } <
    Label basic color = 'black'
    pointing = 'left' > {
      likeCount
    } <
    /Label> <
    /Button>
  )
}

const LIKE_POST_MUTATION = gql `
    mutation likePost($postId: ID!){
        likePost(postId : $postId){
            id
            likes{
                id username
            }
            likeCount
        }
    }
`

export default LikeButton;

标签: javascriptreactjsgraphqlapollo-server

解决方案


const cache: new InMemoryCache({
  typePolicies: {
    getPosts: {
      likes: {
        merge(existing, incoming, {
          mergeObjects
        }) {
          // Correct, thanks to invoking nested merge functions.
          return mergeObjects(existing, incoming);
        }
      }
    }

  }
})


推荐阅读