Creating a thumbs up feature in an Angular 13 application

I've been working on implementing a like functionality in my project, but I've hit a roadblock. Essentially, what I'm trying to achieve is this: when a user clicks the like button, it should change the color of the like icon (fill it) and display the number of likes dynamically. Even after refreshing the page, I want the 'filled' like button to remain visible, like in this image:

https://i.sstatic.net/BEPX9.png

The initial part of the implementation seems to be working fine, but upon page reset, it reverts back to its original state as shown here:

https://i.sstatic.net/zz22J.png

Is there a way to ensure that if a user refreshes the browser, a previously liked post remains liked, and if it's already liked and clicked again, it unlikes? Here's some sample code I've tried so far:

HTML

<div class="likes">
        <div *ngIf="!isLiked">
          <i class="fa fa-heart-o" (click)="likeTweet(tweet.id)"></i>
        </div>
        <div *ngIf="isLiked">
          <i class="fa fa-heart" (click)="unlikeTweet(tweet.id)"></i>
        </div>       
        <div class="likes-count">
        {{getLikes}}
        </div>
      </div>

Component

 isLiked: boolean = false;
 
    like: Like = new Like();

    likeTweet(tweetId: number){
      this.likeService.likeTweet(tweetId, this.like).subscribe(response => {
        this.like = response;
        this.isLiked = true;
      });
    }

    unlikeTweet(tweetId: number){
      this.likeService.unlikeTweet(tweetId).subscribe(response => {
        console.log(response);
        this.isLiked = false;
      });
    }

    getTweetLikes(){
      const tweetId = this.route.snapshot.params['tweetId'];
      this.likeService.getTweetLikes(tweetId).subscribe(response => {
        this.likes = response;
      })
    } 
    likes: LikeModel[];

    get getLikes(){
      return this.likes.length;
    }

Service

  url: string = environment.apiBaseUrl; // localhost:8080
  constructor(private http: HttpClient) { }

  likeTweet(tweetId: number, like: Like){
    return this.http.post<Like>(`${this.url}/like/tweet/${tweetId}`,like);
  }
  unlikeTweet(tweetId: number){
    return this.http.delete<Like>(`${this.url}/unlike/tweet/${tweetId}`);
  }
  getTweetLikes(tweetId: number){
    return this.http.get<LikeModel[]>(`${this.url}/tweet/${tweetId}/likes`);
  }

Entities

export class Like {
    id: number;
    likedTweet: Tweet;
    likedComment: Comment;
    user: User;

}

export class LikeModel {
    username: string;
}

relationship https://i.sstatic.net/1Kpqd.png

Answer №1

Hello Ruschisb,

I noticed that in your function getTweetLikes(), the property isLiked needs to be updated as it always returns false.

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I prevent all permission requests in Electron Security?

I'm currently in the process of enhancing the security of my Angular/Electron application. For this purpose, I decided to utilize electrongravity which has proven to be effective in identifying misconfigurations and prompting me to establish a permis ...

Using Angular 4 Material to pass an array of objects to a dialog box

Greetings, I am currently attempting to pass an array of objects to a Material dialog. Below is my approach: Model export interface IProducts{ recordname: string; comments: [{ comment: string }] } The component class contains the ...

Can the Date class be expanded by overloading the constructor method?

In my dataset, there are dates in different formats that Typescript doesn't recognize. To address this issue, I developed a "safeDateParse" function to handle extended conversions and modified the Date.parse() method accordingly. /** Custom overload ...

Having trouble getting the onClick function to work in your Next.js/React component?

Recently, I delved into using next-auth for the first time and encountered an issue where my login and logout buttons' onClick functions stopped working when I resumed work on my project the next day. Strangely, nothing is being logged to the console. ...

steps for invoking a different component method

I am struggling to figure out how to render the workload component's learningHours method after the setStatusOfUser() method in confirmation.ts. Can someone please help me with this issue? Here is my confirmation.ts component: import { Component, Inj ...

Using act() in React/Jest/MSW causes errors when waiting for a response

As I delve into learning how to unit test with React, my focus has shifted towards using TypeScript. Unfortunately, the course I am taking does not cover most errors related to TypeScript. In my testing journey, I have set up a simple testing function with ...

Manipulating the max property within the ion-datetime component in Ionic 2/3 results in adjusting the default year to its maximum value

Exploring the functionality of ion-datetime in my Ionic 2/3 app, I encountered an issue with the datepicker component. While everything seems to be working fine overall, I am facing a specific problem related to setting max attributes on dates. Within my ...

This component is not compatible with JSX syntax and cannot be used as a JSX component. The type '() => Element' is not suitable for JSX element rendering

My Nextjs seems to be malfunctioning as I encountered the following error in a Parent component. Interestingly, the Spinner Component remains error-free Spinner.tsx export default function Spinner() { return ( <div className='flex ...

Crafting questions to uncover the correct application of the concept of "side effects" in ngrx/effects

I am seeking clarity on whether my approach is correct. After researching examples online, I have noticed a common pattern in handling add and delete actions in both the state and remote database: effects.ts: @Effect() add$ = this.action$ .ofType(ADD ...

Angular 6 has numerous modules that have similar names but vary only in their letter casing

After running ng serve, I encountered an error that has me stumped. Everything was working fine with the new service I created until suddenly it all crashed :( I tried troubleshooting everything possible but to no avail. Even Google didn't provide any ...

What is a simple way to exclude a prop from a declaration in a React/TypeScript project in order to pass it as undefined

I'm trying to accomplish this task but encountering a typescript error indicating that the label is missing. Interestingly, when I explicitly set it as undefined, the error disappears, as shown in the image. Here's how my interface is structured ...

Creating reusable components in Vue.js can enhance code reusability and make development

I am new to Vue.js and WebUI development, so I apologize in advance if I make any mistakes. Currently, I am exploring how to create reusable components using Vue.js. Specifically, I am working on a treeview component with the ability to customize the rend ...

Interface for exporting TypeScript models

I am a beginner in TypeScript and have a question regarding the code where the (position) is referencing another TypeScript model. Both models are located in the 'model' folder: export interface Group { name: string; opportunities: Opportu ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

illustrating an embedded image within angular2

Currently tackling a project in Angular2, where the task involves loading an image directly from a database (base64 encoded). In Angular1, one could easily achieve this with the following code: <img data-ng-src="data:image/jpg;base64,{{entry.img}}" /&g ...

Extract HTML content using CKEditor

Hey there! I'm in need of some help with getting user-entered data from a textarea. I've already attempted using CKEDITOR.instances.editor1.getData() and CKEDITOR.instances.ckeditor.document.getBody.getHtml(), but unfortunately both only return ...

Why do the RouteConfig and classes necessitate the inclusion of a service and router in their constructors?

While working with a sample code in the Angular2 framework, specifically the Heroes sample, I have encountered something that I am struggling to understand. What determines the order of dependencies in the constructor, like Router, Service or vice versa? ...

Modifying a Component's Value in its Template Based on an IF Condition in Angular 6

How can I display or hide the 'separator-container' based on a specific condition in the row data? The condition to satisfy is mentioned as "myConditionCheck" in the 5th line of code. I attempted to achieve this by using "isWarningSeperatorVisib ...

Can the inclusion of additional parameters compromise the type safety in TypeScript?

For demonstration purposes, let's consider this example: (playground) type F0 = (x?: string) => void type F1 = () => void type F2 = (x: number) => void const f0: F0 = (x) => console.log(x, typeof(x)) const f1: F1 = f0 const f2: F2 = f1 f ...

Displaying an Array in HTML using Angular

Just starting out with Angular and experimenting with data display from an array. The data in the array is: [Me, Three, Four] I attempted to loop through it for printing but encountered issues. Here's a snippet of how I'm currently handling it: ...