Session variables should be minimized and while developing an application, I tried something new.
I would like feedback to know if what I am doing has unintended side effects but a good solution I found was creating “global” ReactiveVars. I created a folder imports/api/globals and added an index.js.
index.js defines and exports my ReactiveVars:
const neededEverywhere = new ReactiveVar();
export { neededEverywhere };
Now in any template, I can import { neededEverywhere } from '/imports/api/globals' and call get and set. Reactivity works as expected from Session variables.
Haven’t you just recreated Session in a more cumbersome way? What’s the difference? I suppose it might help prevent some accidental name clashes maybe?
I suppose it’s not such a bad idea though, especially when working in a team. It forces you to initialize each variable you use in a central location, creating a nice list.
I understand that they recreated session variable functionality but they are not accessible truly globally which is what I wanted. Before, I had a session variable that I changed through the browser console and ultimately wanted the same visibility of the variable to different templates but obscured from the window object.
The other advantage to importing the ReactiveVar is that modern JavaScript tools can provide autocomplete, TypeScript/Flow can do static analysis to verify.
Also Session variables have some potentially surprising behaviors that are useful when wanted but can cause unexpected errors if not. I’m talking about the fact their values are preserved across hot reloads.
In my opinion session variables has gotten a bad name because of misuse. They are like Whisky - perfect for the right occasion but a path to destruction and agony if used everywhere, all the time.
Don’t fear session variables. Changing their flavor does not reduce the danger.
The real problem is using Session for local template state, which I think in the early days of Meteor was pretty common, because Blaze didn’t have a built-in solution for it. I really think all templates ought to have been initialized with a “state” ReactiveDict on them by default.
That’s right. And using Session for passing “state” between peer templates is completely acceptable – probabbly the preferred way to do it (I don’t like passing state over the URL when I can get away from it).
Also, using an imported Session is fine, and I suppose “points” you back to the declaration location – which could be helpful to some.