'Update UI based on wether user has liked post or not

I am building a social media app using MongoDB, GraphQL, and Flutter. The user will be able to like and unlike a post. On the frontend, I am able to get the user to like and unlike the post, but the issue I am facing is how to change the UI to indicate the user has liked a particular post? Currently, there is an array called likes that hold all the users who have liked a particular post. I am not able to loop through this array to check if the current user has liked the post or not.

GraphQL Resolver:

async likePost(_, { postId, username }) {
      const post = await Post.findById(postId);

      if (post) {
        if (post.likes.find(like => like.username === username)) {
          post.likes = post.likes.filter(like => like.username !== username);
        } else {
          // post not yet likes, like it
          post.likes.push({
            createdAt: new Date().toISOString(),
            username: username,
          });
        }
        await post.save();
        return post;
      } else throw new Error("Post not found");
    },

GraphQL Query:

query getPosts{
 getPosts {
  id
  body
  likesCount
  likes {
   username
  }
 }
}

Post Card

return GestureDetector(
 onTap: (){
  mutation(<String, dynamic>{
   "postId": result.data!['getPosts'][index]['id'],
   "username": user!.displayName,
  });
 },
 child: result.data!['getPosts'][index]['likes']['username']
  == user!.displayName ? Text("Liked") : Text("Not Liked"),
);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source