ReactiveVar array reference issue

ReactiveVar is great but this case was a pain to debug:

var rv = new ReactiveVar([]);

var foo = rv.get();

foo.push({bar: 'bar'});

console.log(rv.get()); // rv returns array of size 1 with the {bar} inside it

I understand that this is because of how js arrays work but I think this breaks the purpose of using ReactiveVar.

What are your thoughts about this case ?
What are your patterns to prevent this ?

1 Like

I don’t quite understand what the issue is here - is it that you want to make changes to the foo array and not have them made to the ReactiveVar? If that’s the case you can just clone the array when you get it from the ReactiveVar. Something like:

var rv = new ReactiveVar([]);
var foo = rv.get().slice(0); // foo is now a separate array
foo.push({bar: 'bar'});
console.log(foo); // returns array of size 1 with the {bar} inside it
console.log(rv.get()); // returns []
2 Likes