Reactive array is empty

53 Views Asked by At

I'm using Meteor CollectionFS to upload files. I'm using ephmer:reactive-array to store the file IDs after they're stored in the collection. The following is the code:

Template.myFileHandler.created = function () {
    this.fileIds = new ReactiveArray();
}

I upload the files as specified in the CollectionFS documentation:

Template.myFileHandler.events = function () {
    'submit #myFileForm': function (event, template) {
        for(var i = 0; i < fileList.length; i++) {
            var fsFile = FS.File(fileList[i]);
            UserDocuments.insert(file, function (err, fileObj) {
                Template.instance().fileIds.push(fileObj._id);
            });
        }
        console.log(Template.instance().fileIds.get().length)
    }
}

When I do the console.log, I'm getting the length: 0. How do I store the IDs in the reactive array?

1

There are 1 best solutions below

0
Gaëtan Rouziès On

You are just passing a callback in your insert function. But the callback is asynchrous, and will only execute after the insert is done.

So your code is still working. Try putting your console.log in your callback like that :

Template.myFileHandler.events = function () {
    'submit #myFileForm': function (event, template) {
        for(var i = 0; i < fileList.length; i++) {
            var fsFile = FS.File(fileList[i]);
            UserDocuments.insert(file, function (err, fileObj) {
                Template.instance().fileIds.push(fileObj._id);
                console.log(Template.instance().fileIds.get().length); // Here it will show 1
            });
        }
        console.log(Template.instance().fileIds.get().length); // Here, the insert hasn't happened yet
    }
}