Persistent global variable

I have a variable that will be initialized to 0 and incremented upwards from there. But when the user(s) closes the app, it should retain it’s (> 0) value for the next time the app is run.

How can I go about this?

Thanks

Put it in a Collection

Ok, that’s what I was thinking. But if I initialize the value to 0 in /lib/collections/constant.js …

won’t that value be re-initialized when I run the app?

I recommend using a fixtures file:

import { Meteor } from 'meteor/meteor';
import { myCollection } from '/imports/api/myCollection';
Meteor.startup(() => {
    // if the collection is empty
    if (myCollection.find().count() === 0) {
        const data = [
            //...
        ];
        data.forEach(item => myCollection.insert(item));
    }
}

Or, in your case since you have a collection that works like a state and only holds one document:

import { Meteor } from 'meteor/meteor';
import { myCollection } from '/imports/api/myCollection';
Meteor.startup(() => {
    const oldState = myCollection.findOne('state');
    const newState = {
        //default keys here,
        ...oldState, // copy existing vars over the top for persistence on restarts
    }
    myCollection.upsert('state', newState);
}
1 Like