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?