Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data.

listData contains all the necessary information.

All variables have relevant data stored in them.

For example: 1, 1, my title, post text

The result is successfully returned to the service. However, I encounter an issue after that.

update(id, userId, title, body) {
    this.apiService.updateById(id, userId, title, body).subscribe(
      result => {
        console.log(result);

        // THE ISSUE BEGINS HERE
        const currentItemIndex = this.listData.findIndex((item: {id: number}) => item.id === id);

        console.log(`CurrentIndex is: ${currentItemIndex}`); // Returns -1

        // THIS PART IS NEVER EXECUTED
        if (currentItemIndex > -1) {
            this.listData.splice(currentItemIndex, 0, {userId: userId, title: title, body: body});
        }

      },
      error => {
      console.log('There was an error: ', error); // No errors returned
    }
  );

}

Any suggestions on how I can resolve this? What could be causing the problem?

Answer №1

Kindly utilize the findIndex method in this manner:

this.listData.findIndex((item) => item.id === id);

I believe specifying the type of item as an argument for findIndex is inaccurate

let listData = [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }]
  
  // assuming the id we are looking for is 2
  
  let id = 2;
  
  let foundIndex = listData.findIndex((eachData) => {
    // === works with integers, does it match your case? 
    // if not, try using ==
    return eachData.id === id;
  });
  
  console.log(foundIndex)

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

Loop through every element in the Angular2 template

I am working with the following template and I need to access all the elements within it. Using ViewChildren only gives me a reference to one element, most likely because no two elements are the same and I am not using the same directive/component inside t ...

Error: The variable "Set" cannot be found in the react.js code, specifically in Safari browser

An issue has been identified in Safari where a ReferenceError is thrown: "Can't find variable: Set" when using react.js. This error occurs only in Safari, while all other browsers work perfectly fine. The error message points to the main.js file which ...

`Managing a large set of options with Angular Material Select``

Currently, I am utilizing the Angular Material select form control to populate a list of options. However, I have encountered an issue where the list could potentially contain up to 100k elements. Although storing this large list is not problematic, displa ...

Collapse the sidebar using React when clicked

Just beginning to learn about React and I'm trying to figure out how to toggle the open/closed state of a react-pro-sidebar component using a click event: export default function MaterialLayout(props) { const { children } = props; const classes = us ...

javascript triggering before its designated event happens

I've encountered a puzzling issue with a complex file where a javascript function is behaving unexpectedly—it seems to be firing before its designated event actually takes place. I have ruled out the possibility of an onload event triggering this be ...

Guidelines for choosing input using jQuery

I am looking to retrieve the value of an input using jQuery. Specifically, I need to extract the value of a hidden input with name="picture" when the user clicks on the حذف این بخش button by triggering the function deleteDefaultSection( ...

Ways to utilize jquery to limit the length of an editable div and prevent it from exceeding our specified restriction

Imagine a scenario where you have the following code snippet: <div id="editing" contenteditable onclick="document.execCommand('selectAll',false,null)">Put text here...</div> In this situation, let's say you want to impose a r ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

Calculating the sum of all values in the database

In my database, I have a value called task_time. I want to add this value to itself so that the total time is calculated as totalTime = task_time + task_time + ... + task_time. This is how I retrieve the data: function getEndTasks() { $http.get(& ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

What steps can be taken to successfully import a JavaScript module without encountering a ReferenceError?

Recently, I created a Javascript export file with the following content: export const A = 1; export const B = 2; export const C = 3; As an experiment, I attempted to import this file into another Javascript document like so: import 'path/export_file. ...

Generate app registration in Azure Active Directory by automatically setting up credentials using the administrator's username and password

I am encountering a challenge that I currently cannot comprehend. In my growing list of over 100 different tenants, I aim to automatically create an app registration for each tenant with specific API permissions granted. Upon my initial login to an Azure ...

Issues arise when JQuery functions fail to execute

This unique program showcases a series of error messages that are designed to appear under specific conditions. These conditions are identified through PHP code, following which the essential JQuery script is echoed via PHP to display the messages. Initia ...

Configuration of injected services in IONIC 2

I am curious about how the services from injected work in IONIC 2. Specifically, my question is regarding the number of instances that exist when one service is used in two or more controllers. Previously, I asked a colleague who mentioned that IONIC 2 op ...

Mocking is not working for request scoped injection

I'm encountering an issue with mocking the return value of a provider, as it seems to be clearing out the mock unexpectedly. Module1.ts @Module({ providers: [Service1], exports: [Service1], }) export class Module1 {} Service1.ts @Injectable({ ...

The Socket.io Chat application is indicating a memory leak with the EventEmitter, detecting 11 listeners that have been added. To resolve this issue

My private chat application is built using socket.io, node.js, and MySQL. However, I encountered an error when trying to use socket.on('example', function(data){...});. The error code thrown is related to a possible EventEmitter memory leak with ...

The React-Big-Calendar Drag and Drop feature in the month view consistently drags events from the leftmost column

I'm seeking assistance with a bug I've encountered while using the big-react-calendar. The issue arises when dragging an event, as it consistently moves to the leftmost column regardless of mouse position. However, shifting the event to a differe ...

Acquire data from an HTML Element

I was provided with the following div that was already created for me: <div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1 ...

Utilizing a different file to arrange and establish state

In a separate file called Origin.js, I have some data (objects) stored. This data is exported using the spread operator within an object named OriginState: Origin.js //info const info = { title: '', year: '', }; //images const ...

Determine if a condition is met in Firebase Observable using scan() and return the

Within Firebase, I have objects for articles structured like this: articles UNIQUE_KEY title: 'Some title' validUntil: '2017-09-29T21:00:00.000Z' UNIQUE_KEY title: 'Other title' validUntil: '2017-10-29T21:00:00 ...