Yasho Sagar
Yasho Sagar

Reputation: 123

Reactive array is empty

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?

Upvotes: 0

Views: 51

Answers (1)

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
    }
}

Upvotes: 1

Related Questions