AntonioSk
AntonioSk

Reputation: 526

Check a value in two objects

I am building a social media app. My problem is that I want to display either a 'follow' next to the user who is following me if I don't already follow him. Or an 'unfollow' button if I already follow the user. I am trying it for hours but can't find the right solution. Could someone reach out and help I would really appreciate it!

Component:

export class HomeComponent implements OnInit {
  users: IUser[] = [];
  following: IUser[] = [];
  followers: IUser[] = [];
  username = "";

  constructor(private _userService: UserService) { }

  ngOnInit(): void {
    localStorage.setItem("gd", "78F88FC0-7A58-49CD-881E-4B36C5C29B71");
    this.getUsers();
    this.getFollowing();
    this.getFollowers();
  }

  checkIfUserFollowsFollower(name) {
    /*
        * Check if name exists in this.following
        * If so return true
    */
  }

  getUsers() {
    this._userService.getUsers().subscribe(res => {
      this.users = res;
    })
  }

  getFollowing() {
    this._userService.getFollowing().subscribe(res => {
      this.following = res;
    })
  }

  getFollowers() {
    this._userService.getFollowers().subscribe(res => {
      this.followers = res;
    })
  }

  followUser(gd) {
    this._userService.followUser(localStorage.getItem("gd"), gd).subscribe(
      res => {
        console.log(res);
      }
    )
  }

  unfollowUser(gd) {
    this._userService.unfollowUser(localStorage.getItem("gd"), gd).subscribe(
      res => {
        console.log(res);
      }
    )
  }
}

HTML:

<h1>Followers:</h1>
<div class="user-profiles">
    <div class="user-profile-container" *ngFor="let user of followers">
        <div class="user-profile-img">
            <img src="../../../assets/profielfoto.jpg" alt="" srcset="">
        </div>
        <div class="user-profile-content">
            <h2>@{{ user.username }}</h2>
            <h5>{{ user.fullname }}</h5>
            <!-- TODO check if user follows them, depending of output show different button -->
            <button *ngIf="checkIfUserFollowsFollower(user.username)" (click)="unfollowUser(user.gd)" mat-raised-button
                color="primary">Unfollow</button>
            <button *ngIf="!checkIfUserFollowsFollower(user.username)" (click)="followUser(user.gd)" mat-raised-button
                color="primary">Follow</button>
        </div>
    </div>
</div>

Upvotes: 0

Views: 38

Answers (1)

audzzy
audzzy

Reputation: 741

you could do something like this..

   checkIfUserFollowsFollower(name) {
        /*
            * Check if name exists in this.following
            * If so return true
        */
        return (this.following.filter(x => x.username === name).length > 0);
   }

Upvotes: 2

Related Questions