The following code loops
const route = new ReactiveVar (['login'])
Tracker.autorun(() => {
const u = Meteor.userId()
if (!u) {
console.log("before", route.get())
route.set(['login'])
console.log("after", route.get())
}
})
With the following message
before ["login"]
after ["login"]
before ["login"]
This is due to ReactiveVar using pointer equality by default, the reactive var doesn’t recognize the array is already [‘login’] and updates, which triggers the autorun. Simple fix is to provide a custom equality function that computes structural equality.
const array_eq = (a, b) => {
if (a == null && b == null) return true
if (!a || !b) return false
if (a.length != b.length) return false
for (let i = 0, leni = a.length; i < leni; i++) if (a[i] != b[i]) return false
return true
}
That said, is it possible to prevent the autorun from depending on the reactive variable ? That is, to only trigger when there is a change in Meteor.userId() and not in routes ?