How to get the old value of a reactive data source in Meteor?

236 Views Asked by At

I am looking for a way to get old value of a reactive data source in Meteor. Say I have this code:

const foo = new ReactiveVar(1);

Tracker.autorun(() => {
  const fooNewVal = foo.get();

  if (/* compare based on fooNewVal value */) {
    // do something
  }
});

foo.set(2);
foo.set(3);
foo.set(4);

What I want is somehow to get the old value of foo, use this old value with the new value to decide execution of if statement, like:

const foo = new ReactiveVar(1);

Tracker.autorun(() => {
  const fooNewVal = foo.get();
  const fooOldVal = foo.getOld();

  if (fooNewVal - fooOldVal === 1) {
    // do something
  }

  if (fooNewVal - fooOldVal === 2) {
    // do something
  }

});

foo.set(2);
foo.set(3);

I know I could use a normal variable to store the old value at the end of the autorun function:

const foo = new ReactiveVar(1);
let oldValue = 1;

Tracker.autorun(() => {
  const fooNewVal = foo.get();

  if (fooNewVal - oldValue === 1) {
    // do something
  }

  if (fooNewVal - oldValue === 2) {
    // do something
  }

  oldValue = fooNewVal;
});

foo.set(2);
foo.set(3);

Although it works, it does not look "right" for me. I searched Atmosphere and Npm but could not find a solution. Do you know any solutions or packages/modules to get around this?

1

There are 1 best solutions below

1
Mikkel On

What you are doing is fine. It's a common practice to store a previous version of a variable. If you were fetching from the database, the data at the beginning of the autorun function will still be the old value. Autorun is triggered when the reactive variable changes, so in your case foo has already changed on entry.