【问题标题】:Cache data may be lost when replacing the getPosts field of a Query object. Apollo替换 Query 对象的 getPosts 字段时,缓存数据可能会丢失。阿波罗
【发布时间】:2021-04-25 18:26:32
【问题描述】:

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

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;

【问题讨论】:

    标签: javascript reactjs graphql apollo-server


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 1970-01-01
      • 2021-05-25
      • 2021-08-01
      • 2017-08-01
      • 2019-01-31
      • 2019-02-20
      • 2021-08-20
      • 2018-06-13
      相关资源
      最近更新 更多