Set Keys of ReactiveVar object

Hi!

I’m trying to do the following

Template.Collection.onCreated(function () {
    const self = this;
    self.foo = new ReactiveVar({});
});

//in some handler
template.foo.set(fizz:'buzz');

I’d then want to expect

template.foo.get() == {fizz:'buzz'}

My workaround for now is to create an object first, and then set foo to that. I.e.

const obj = {fizz:'buzz'};
template.foo.set(obj);

//then this works fine to retrieve the set obj
const results = template.foo.get();
results.foo == {fizz:'buzz'};

Just wondering if there’s any roundabout way to achieve this in ReactiveVar so that I don’t have to introduce another temporary variable.

Any insights?

template.foo.set(fizz:‘buzz’);

That is not valid javascript. Try:

 template.foo.set({fizz:'buzz'});

You may want to use a Reactive Dict instead: https://docs.meteor.com/api/reactive-dict.html

2 Likes

Sorry, that was a typo. I meant more in terms of how to set keys to the object after. I.e.

template.foo.set({fizz:'buzz'});

is gonna make it so that foo is always that object. But what if I wanted to add another key? Any way to do that in the library itself, or ReactiveDict the alternative?

template.foo.set({fizz:'buzz', foo: 'bar'});

Now it has two keys!

But really, If you want to track key value pairs independently, use a ReactiveDict:

    self.foo = new ReactiveDict();
template.foo.set('fizz', 'buzz');
template.foo.get('fizz') == 'buzz' // true
template.foo.set('foo', 'bar');
template.foo.get('fizz') == 'buzz' // true
template.foo.get('foo') == 'bar' // true
2 Likes

Perfect, thanks so much for the example