"Using the fetch Prototype.json() method can lead to the alteration or corruption of the

For the past week, I've been struggling with a seemingly impossible issue in my Javascript code:

The problem arises when trying to retrieve data from the server using fetch:

fetch(this.props.url, {
            method: 'POST',
            body: JSON.stringify({
                class: 'property',
                action: 'view', 
                objectId: this.props.element.id,
                token: this.props.token,
            }),
        })
            .then(response => response.json())
            .then(json => {
                console.log(json);})

Oddly enough, testing with Postman yields the correct result:

"units": [
            {
                "amount_due": 22.0,
                "id": 31,
                "floor": 5,
                "common_percentage": 0.012223,
                "building": {} 
            },
            {
                "amount_due": 16.0,
                "id": 33,
                "floor": 5,
                "common_percentage": 0.012143223,
                "building": {} 
            }
         ]

However, my console logs both units as having an ID of 33.

I have meticulously checked the backend multiple times and it returns the correct data. Postman confirms this. I even attempted parsing the response using .text() instead of .json(), and .text() does return the accurate data. The unexpected outcome occurs only with .json(). Am I losing my mind or have I stumbled upon a bug (or quirk) with the .json() method?

Thank you.

EDIT 1:

Thanks to @ChrisG, I discovered that my code is somehow altering the data. This happens after calling this.setState:

// Code snippet excluded for brevity

One thing to note: the problematic "units" section is a property of the 'property' object. Could it be plausible that 'property' is some kind of reserved word causing issues?

EDIT 2:

I pinpointed the issue to this line of code:

this.setState({element: json.property})

Any thoughts on how to resolve this?

Answer №1

After some investigation, it appears that the issue can be traced back to the this.setState() function which seems to be causing data corruption. Fortunately, the fetch response.prototype.json() is working correctly. I will create a new bug report to address the root cause of the problem. Special thanks to @ChrisG for guiding me in the right direction.

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

Effective Ways to Transfer Input Parameters to Karate File using npm

I am working on a test script that runs a series of queries. In order to execute the file, I need specific inputs such as URL and authorization header, which will vary depending on the environment. How can I prompt the user for these inputs in the command ...

Combining a 3D array into a 2D array with the addition of HTML tags around each value using JavaScript

3D array // Array var x = { "letter": [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ], "line": [ { "data": [ 306, 830, 377, 651, 547, 369, 300, 148, 494 ] }, { "data": [ 88, 339, 298, 87, 96, 108, 93, 182, 64 ] }, { "data": [ 3157, 2943, ...

Guide to deserializing JSON with a dynamically changing root key

I am having difficulties working with this JSON data. {"1234345": [{ "queue": "XXX", "name": "XXXXX", "entries": [{ "points": 54, "isInactive": false, }], "tier": "ASDF" }]} However, the JSON data can also have a different structure: ...

What is the reason that the keyword 'in' does not function for verifying the presence of a particular word within an array in JavaScript?

Currently, I am focused on string manipulation for a chatbot. My main objective is to identify a specific word within a returned string message. Here is an example of my approach: let msg = 'how are you?' //An illustration of ...

JavaScript: Invoking a nested function within a namespace

script1.js var MyNamespace = {}; MyNamespace.addNewFunction = function(a,b,c) { function doSomething() { // Perform some action here } } script2.js MyNamespace.addNewFunction.doSomething() ?? I’m a bit unsure on how to access the content ...

What is the best way to retrieve the current value of a header cell, including any nested headers?

My handsontable has headers that include checkboxes and select boxes. How can I access the headers to check the value of a select/checkbox inside the header cell? You can view an example in this JSFiddle (with nested headers - same as my project): http:/ ...

Is it possible to dynamically import a Vue.js component based on a prop value?

Currently, I am utilizing the Material design Icons library specifically made for Vue.js. In this library, each icon is a standalone file component within its designated folder. Within my project, I have a separate component called ToolbarButton, which in ...

Retrieve the parent element's value based on the child using jQuery

Code: { "endpointAgents": [ { "agentId": "MyId", "agentName": "MYNAME", "location": { "locationName": "location" }, "clients&qu ...

How should elements be properly inserted into injected HTML code?

We are currently phasing out our custom forms in React on the website, and transitioning to Microsoft Dynamics 365 generated forms. These new forms are injected through a React placeholder component created by a script that loads the js bundle and inserts ...

Unable to convert the existing JSON array into the specified type

I've been struggling to find a solution to this problem, even though I've come across similar topics that have been asked before. Below is a sample Json that I'm posting to a web API controller: { "AppointmentId ":2079, "ma ...

Populate select2 with the selected value from select1 without the need to refresh the page or click a button

Being a novice in PHP and Javascript, I am looking for a way to populate the "info" select dropdown based on the selected value from the "peoplesnames" dropdown without refreshing the page or using a button. Here's my code: HTML: <select id="peo ...

Banning the use of server-side rendering | Advantages and Disadvantages

My PHP server has transitioned to just being a data pump, while HTML is now composed on the client side using JavaScript. Advantages Reduces network load by sending raw data instead of HTML Lowers server load as it does not have to handle HTML compositi ...

What is preventing Javascript from executing a function when there is an error in another function?

Can you explain why a JavaScript function fails to run if there is an error in another function? Recently, I encountered an issue on my HTML page where the alert from the popup1() function would not load. It turns out the problem stemmed from an error in ...

Display the output returned from the AJAX request (HTML and/or JavaScript)

How can I effectively render content from an ajax call when the response may include html and/or javascript? I used to rely on document.write() for synchronous calls, but now that I need to use asynchronous calls, I have to find a different approach to dis ...

Front-end procedural logic for increasing identification values

$scope.items.push({ "itemId": $scope.tabId + 1, "itemName" : itemName, }); Whenever I try to push the item, I always console.log($scope.itemId) but it remains the same without increasing. One way to handle this issue could be utilizing $http after each ...

Converting a JSON Response to a Pandas Dataframe

I am attempting to retrieve an API response from and convert it into a Pandas Dataframe. Specifically, my goal is to extract the 'Points' array and load it into the data frame. I have tried using json_normalize as suggested in other posts, but a ...

The contact form displays a confirmation message indicating successful submission, however, it fails to actually send the email

Having issues with a PHP script I created for the contact page on my website. After a user fills out and submits the form, they see a success message but the email is not sent. Can someone review this script and point out where I went wrong? <?php ...

What is the proper way to request permission for allowing others to access the mailto function?

I want to create a feature where users can open email on click using JavaScript. However, I have encountered an issue with using the mailto function in Chrome, as it requires changing the handlers settings to make it work. My query is whether it is possib ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

When utilizing an API to render text into a div, the offsetHeight function may return 0

I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more button if the text exceeds 3 lines. Here is my approach: seeMore(){ this.setState({ seeMore: !this.state.seeMo ...