DEV Community

Discussion on: Built a social media website with Next JS, TailwindCss and Firebase in 8 days

Collapse
namanvyas profile image
Naman vyas Author • Edited on

That's how I created like functionality :

  1. While creating post document create a subcollection for like.

  2. In like subcollection create a document called count or total anything you want with initial value of 0 we will use this document to store total likes count ( there are other ways but they will cost more read request when you call, not good for large collections)

  3. Now when we load post on frontend we read total or count document from like subcollection to get total like count.

  4. Now the thing is we have to check if current user is already liked the post or not so for that when someone like a post we create a document in like subcollection of post with there uid or username because both are unique.

  5. Now when a post load, we will check if there is any document available with current user username or uid if yes then I use react-hook(usestate) to change a variable(AlreadyLiked) value to true and with this true or false i use ternary operator to update UI and onclick function
    for example :
    // if alreadyliked is true change like button color to purple.
    {AlreadyLiked == true ? Color.purple : Color.white }
    // if alreadyliked is true call dislike function.
    {AlreadyLiked == true ? Dislike() : AddLIke() }

  6. and if variable value is false, when user click it will call a function that increment total count value with one create a document with users uid or username and change AlreadyLiked value to true.

Hope this information will help you :-)