Home > other >  Javascript global variable not updating
Javascript global variable not updating

Time:10-25

I am trying to access the dataCount variable from another file after its been updated by updateData function which takes an array as a parameter and as the pop function returns the new length I have passed that directly to the updateStatus function. But even after updating it and accessing it stills gives me 0.

// status.js file

var dataCount = 0;
let data = []

function updateStatus(num, opp){
    if (opp == "add"){
        dataCount  = num
    } else if (opp == "sub") {
        dataCount -= num
    } else {
        dataCount = num;
    }
}

function updateData(arr){
    updateStatus(data.push(arr), 'update');
}

module.exports = {
    dataCount: dataCount,
    updateStatus: updateStatus,
    data: data,
    updateData: updateData
}

// middleware.js file

const status = require('./status');
const methods = require('./helperFunctions')

class Middleware{
    constructor(){
    }

    async populateIfLess(req, res, next){
        if (status.dataCount < 4){
            try {
                // Fetches the data from database and stores in data
                const data = await methods.fetchMeaning();
                Object.entries(data).map(entry => {
                    status.updateData([entry[0], entry[1]])
                })
                methods.log('Data populated on')
                setTimeout(() => {
                    console.log(status.dataCount)
                }, 1500);
                next()
            } catch (error) {
                methods.log(error);
                res.send({ERROR: "Something went wrong, please check log file."}).end()
            }
        }
    }
}

CodePudding user response:

You are copying the value of dataCount (which is a number so is a primitive) to a property of an object, then you are exporting the object.

Later you update the value of dataCount which has no effect on the object because numbers are primitive (and not handled by reference).

You need to modify module.exports.dataCount instead.

  • Related