Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript global variable not updating

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
            }
        }
    }
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading