Home > Back-end >  Cannot push JSON elements to array inside for loop called from useEffect
Cannot push JSON elements to array inside for loop called from useEffect

Time:08-29

I have an array candleRealTimeDataQueue which is not getting updated properly. Please find the code below:

    let candleCurrentJSONDataWS = null;
    var candleRealTimeDataQueue = [];
    let tempDateTime = null;
    let candleJsonData = {};


    useEffect(() => {
        getDataFromAPI();
    }, []);

    ...

    const getDataFromAPI = async () => {
        let apiDataFetch = await fetch('https:/api/endpoint');

        let response = await apiDataFetch.json();    // data from api obtained correctly
                                                     // total 4 values
        
        for (var i = 0; i < 4; i  ) {

            tempDateTime = new Date(parseInt(response[i][0]));
            candleJsonData['time'] = tempDateTime.toString();
             
            candleJsonData['open'] = parseFloat(response[i][1]);
            candleJsonData['high'] = parseFloat(response[i][2]);
            candleJsonData['low'] = parseFloat(response[i][3]);
            candleJsonData['close'] = parseFloat(response[i][4]);

            console.log(candleJsonData); // this correctly prints different 
                                         // data for each different i

            candleRealTimeDataQueue.push(candleJsonData);
            console.log(candleRealTimeDataQueue);   // PROBLEM is here: At the end
                                                    // candleRealTimeDataQueue array all
                                                    // have SAME elements. Its wrong. All
                                                    // 4 elements are of i = 3
        }
    }

Problem is at the end candleRealTimeDataQueue has 4 elements and all the elements are same. This should not happen because I am pushing DIFFERENT candleJsonData elements in the candleRealTimeDataQueue array in the for loop. Please help.

CodePudding user response:

I believe the problem here is that you are reusing the candleJsonData object. When you run candleRealTimeDataQueue.push(candleJsonData), you are pushing the reference to candleJsonData into candleRealTimeDataQueue. So at the end of the loop, you have four references to the same object inside candleRealTimeDataQueue. And since you are modifying the same candleJsonData object over and over again, you'll just see four identical json data inside the queue when you log it and all four elements will be of i = 3.

Instead, you should be creating new candleJsonData objects inside your loop. So something like

        for (var i = 0; i < 4; i  ) {

            tempDateTime = new Date(parseInt(response[i][0]));
            let candleJsonData = {}
            candleJsonData['time'] = tempDateTime.toString();
             
            candleJsonData['open'] = parseFloat(response[i][1]);
            candleJsonData['high'] = parseFloat(response[i][2]);
            candleJsonData['low'] = parseFloat(response[i][3]);
            candleJsonData['close'] = parseFloat(response[i][4]);
            candleRealTimeDataQueue.push(candleJsonData);
        }

CodePudding user response:

it is because of the candleJsonData variable which is declared outside, so latest value is overriding previous value. In face there is no need of that variable and it can directly push in the array.

 var candleRealTimeDataQueue = [];

  React.useEffect(() => {
    getDataFromAPI().then((data) => {
      for (let i = 0; i < 4; i  ) {
        candleRealTimeDataQueue.push({
          time: new Date(parseInt(data[i][0])).toString(),
          open: parseFloat(data[i][1]),
          low: parseFloat(data[i][3]),
          close: parseFloat(data[i][4]),
        });
      }
    });
    return () => {
      // do clean up here
    };
  }, []);

  const getDataFromAPI = () => {
    return fetch('https:/api/endpoint');
  };
  • Related