I want to dynamically generate output in my render() but I have run into a very strange situation. I have a process whereby I retrieve some data from a database using a fetch(). Once I get the data back, I determine the number of data records and then execute a for loop to populate an array with the returned data. I have a console.log() before the for loop to display the contents of my data receiving array and another console.log() as I populate the receiving array. For some reason, as I populate a specific occurrence of the array, all occurrences of the array appear to be changing. This is the entire code that I have:
import React from 'react';
import '../styles/app.css';
class testpage extends React.Component {
constructor(props) {
super(props);
this.state = {
productArray: []
};
}
componentWillMount() {
var tempData = '';
var numberOfRecords = 0;
let url = "http://wmjwwebapi-dev.us-west-2.elasticbeanstalk.com/api/getdata";
const options = { method: 'GET' };
fetch(url, options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
if (myJson == undefined)
{
console.log("fetch failed");
}
else
{
//inspect the data that the WebAPI returned
var return_code = myJson[0].return_code;
if (return_code == "Default Return code"){
tempData = '';
numberOfRecords = -2;
} else {
tempData = JSON.parse(myJson[0].return_string)
numberOfRecords = tempData.barcode.length;
var counter = 0;
var productArray = new Array;
var product = {
barcode: '',
name: '',
description: '',
image: '',
price: ''
}
for (counter=0;counter<numberOfRecords;counter++) {
product.barcode = tempData.barcode[counter];
product.name = tempData.name[counter];
productArray[counter] = product;
}
}
}
});
}
render() {
<div>
<div>
{this.state.productArray[0].barcode}
</div>
</div>
}
}
export default testpage;
Here is an image of what I see in the console.log() when the loop counter = 0:
Notice the barcode value of 5000159459228? This value gets pushed into productArray[0].barcode. And this is what I expected.
Here is an image of what I see in the console.log() when the loop counter = 1:
Here, the barcode of the record read is 5000159459230. This value should go into productArray1.barcode, which the image shows it does. However, the image also shows that the value of productArray[0].barcode has changed from 5000159459228 (the value of the first record) to 5000159459230 (the value of the second record).
Here is an image from the 3rd time through the loop:
Again, a new record with barcode = 5000159459231. It appears that this value gets pushed into productArray2.barcode but productArray[0].barcode and productArray1.barcode have now been changed.
How is that possible?
Eventually, the goal is to dynamically render the data that is retrieved.
I thank you in advance for any assistance.