When delving into an object to filter it in Angular 11, results may vary as sometimes it functions correctly while other times

Currently, I am working on implementing a friend logic within my codebase. For instance, two users should be able to become friends with each other. User 1 sends a friend request to User 2 and once accepted, User 2 is notified that someone has added them as a friend. However, when I check if they are friends by iterating from User 1 to User 2, sometimes it works correctly and other times it does not. The issue arises when, even though I am friends with someone, the system prompts me to 'Add as Friend' again, which is undesirable. Interestingly, sometimes a simple page reload fixes this problem. Please note that 'this.data.user' represents the ID of the friend.

I suspect the problem lies in how I handle the request to retrieve all friends, causing this inconsistency.

Below is the snippet of code responsible for checking if users are friends or not, executed within the 'ngOnInit' lifecycle hook.


checkFriend: User[] = [];

if (success[1]) {
    this.data = success[0];
    this.checkFriends(this.data.user);
} else {
    this.modelDataService.getUserModel(this.outsideUserId).subscribe((t: Model) => {
        this.data = t;
        this.loadActiveUserConnections(this.data.user);
        this.checkFriends(this.data.user);
    });
}

this.modelDataService.getOutsideModel(this.outsideUserId).subscribe((t: Model) => {
    this.data = t;
    this.loadActiveUserConnections(this.data.user);
    this.checkFriends(this.data.user);
}); // The issue might arise here due to both being called from outside

checkFriends(id) {
    this.friendService.getAllFriendRequests().subscribe((finalRequesters) => {
        this.checkFriend = finalRequesters;
        this.checkFriend.forEach((oneRequest: any) => {
            console.log(oneRequest);
            if ((oneRequest.friendId === id || oneRequest.friendId === id) && oneRequest.status === "You are friend") {
                oneRequest.isFriend = true;
                this.isFriend = true;
            } else if (oneRequest.friendId === id && oneRequest.status === "Request Pending") {
                oneRequest.uniqueId = oneRequest.userId;
                oneRequest.isRequest = true;
                this.isRequest = true;
            } else {
                this.isFriend = false;
                this.isRequest = false;
            }
        });
    });

}

The following section presents the HTML code:


<a class="px-1" *ngIf="!checkUser">
  <button class="px-3 font-weight-600 btn btn-light" (click)="addFriend()" *ngIf="!isFriend && !isRequest">
    <span class="bi bi-person-plus-fill d-flex align-items-center">
      <span class="pl-2">Add Contact</span>
    </span>
  </button>
  <button class="px-3 font-weight-600 btn btn-light" *ngIf="isRequest">
    <span class="bi bi-person-plus-fill d-flex align-items-center">
      <span class="pl-2">Cancel Contact Request</span>
    </span>
  </button>
</a>

And here is the method for retrieving all friend requests:


getAllFriendRequests() {
  return this.http.get<any[]>(this.apiBaseURL + "/friends");
}

This is what the 'oneRequest' object looks like:


{ 
  createdDate: "2021-03-20T22:24:54.512Z",
  friendId: "602e4c30e3346466703376ab",
  id: "605676360fb6b109209674be",
  status: "You are friend",
  userId: "5fbc1bc72ffec245c4bd7725",
  __v: 0,
  _id: "605676360fb6b109209674be",
  ...
}

'friendId' represents the friend's ID, while 'userId' stands for the authenticated user's ID. Despite this, when I attempt to log 'oneRequest', it returns the entire array instead of a single object.

Lastly, let’s take a look at the backend implementation:


async showUserCV(req, res) {
  ModelData.aggregate()
  let modelData = await ModelData.findOne({userUrl: req.params.id }).populate("user").exec();
  if (!modelData) {
      res.status(204).json({error: "No Data"});
      return;
  }
  return res.status(200).send(modelData);
},

const ModelData = require("../models/data");

Answer №1

When seeking to repeatedly replace the data, consider utilizing map() in place of forEach(). Give this a shot:

this.checkFriend.map((oneRequest: any) => {
  // Insert your desired loop actions here
}

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

Error: Unable to access the 'address' property of a null object

I am a beginner in the realm of react and have encountered an issue with my app, which is a simple e-commerce platform. The problem arises when I try to enter the shipping address during the checkout process, as it throws an error. TypeError: Cannot read ...

Dynamically Loading CSS files in a JQuery plugin using a Conditional Test

I'm trying to figure out the optimal way to dynamically load certain files based on specific conditions. Currently, I am loading three CSS files and two javascript files like this: <link href="core.min.css" rel="stylesheet" type="text/css"> & ...

Receiving errors in React/TS/material-ui when attempting to use a variable as a value for a grid property. Messages include "No overload matches" and "Type 'number' is not assignable to type..."

tl;dr: When using a variable as the value of a grid xs property in JSX, material-ui throws a TS error. I'm working on implementing grids in material-ui with React/TypeScript. The goal is to make the width of a specific element dependent on the quant ...

issue encountered while passing a callback in a res.render() function

Currently, I am working on a small application where I am fetching data from remote JSON files to generate statistics that will be displayed in an EJS file later. My objective is to pass separate values for rendering and then utilize them within the EJS d ...

Utilizing JQuery for retrieving a filename

I have a unique file upload button on my website. To provide the user with visual feedback about their chosen file, I modify the html of a div to display the file name. My jquery code is as follows: $("input[type=file]").change(function() { var filen ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

Interactive hover effect in JavaScript displays a larger version of other thumbnails when hovering over a dynamically loaded thumbnail image, instead of its own full-size image

I recently began teaching myself PHP and Dreamweaver with the help of a video tutorial on building data-driven websites using Dreamweaver. My goal is to create a dynamic table with 6 columns and 20 rows. column1 | column2 | column3 | colu ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

What is the best way to combine 4 small triangle pieces in order to create one large triangle?

Is there a way to create an image background with triangle shapes by combining small triangles together? I am interested in making this collection of triangle image backgrounds. Can someone guide me on how to do it?! .block { width: 0; height: ...

What is the best way to ensure that a Material UI transition component fully occupies the space of its parent component?

I've been experimenting with a Material UI transition component in an attempt to make it completely fill its parent container. So far, I've achieved some success by setting the width and height to 100% and applying a Y-axis translation for the co ...

The MEAN stack consistently shows an error message of 'Invalid password' whenever a user attempts to log in

I have been working on creating a user login system in node.js with mongoose and MongoDB. Everything works fine when registering new users, but after a few successful logins, an error stating "Invalid password" starts to appear. I would appreciate any assi ...

Exploring the possibilities with a Nuxt Site as a foundation

[![enter image description here][1]][1] Exploring the world of nuxt and vue, I aim to build a basic website using vue and then convert it into a static site utilizing: nuxt generate I have successfully accomplished this task with nuxt and vuetify (check ...

The jQuery slider's next button is not functioning as intended

jQuery('#slider-container').bjqs({ 'animation' : 'slide', 'width' : 1060, 'height' : 500, 'showControls' : false, 'centerMarkers' : false, animationDuration: 500, rotationS ...

How should the directory be organized for the param with a prefix in Nuxt.js?

My route is set up as /en/rent-:productSlug How should I organize the directory for this route, considering that the parameter productSlug includes the prefix rent? ...

Link the values of mongoose array to a distinct identifier

This question may come across as vague, but I'll do my best to explain it clearly. Just a heads up, I'm relatively new to working with mongoose :) So, I have this mongoose schema where different values are stored for each user: let userSchema = ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Inconsistency in Firebase data updates

Hey there, my code snippet below is responsible for capturing latitude and longitude values through a drag-and-drop marker. Although the latitude and longitude are continuously updated in the console when I log them, the same doesn't seem to happen wh ...

Mapping routes in ExpressJS

I am interested in developing a programmatic route generator. Within my project, I have a module called ./utils/crud.js structured as follows: const express = require('express'); const router = express.Router(); module.exports = function (Mode ...