0

I want to store blocks of a json file into an array. Here is my current code, in controller (ctrl) :

var ctrl = this;
var id = (location.href).replace(/.*\//g, ''); //use m.route() ?
ctrl.list = [];

m.request({method: "GET", url: "/data/"+id}).then(function(blocks){
    blocks.map(function(block) {
        ctrl.list.push(block);
    });
});

console.log(ctrl.list); //Result : an empty array. Why ?
  • Yes, that's how `m.request` works — `m.route` is used for page changes in your front end application and shouldn't be used for fetching data from the server. What difficulties are you having? – Barney Jun 02 '15 at 04:17
  • @Barney : I have a JSON file at url : "/data/"+id who contains list of blocks, for init my app. A block matches a model with some differences to treat before. –  Jun 02 '15 at 07:33
  • No, because my array is empty. But if I try a console.log just after the line : ctrl.list.push(block), the array is completed by data. –  Jun 02 '15 at 07:57
  • Ah! I see. Have a look at my answer ;) – Barney Jun 02 '15 at 08:05

2 Answers2

0

m.request is an asynchronous operation: it needs to make a request to the server, wait for the server to answer, load the contents, and then give you the response — this is why it implements then: to give you a callback so you can do things with the data when it arrives.

But your console.log is happening immediately after you make the request: the response isn't ready yet. Anything that depends upon the server data needs to be invoked inside the then callback function.

Barney
  • 16,181
  • 5
  • 62
  • 76
0
   controller: function() {
var response = m.prop(); return {
    response: m.request({method:"GET",  
        url:"http://yourUrl", data:{date to send in Json format}}),

in the view

m("ul" , ctrl.response().map(function(folder){
        return [
            m("li" , folder.name),

Folder in this case is the Json that you accept from the server, suppose that you have this in the response ["name" : "Jhon"], with folder.name the value of your li will become Jhon. Remember that m.request want at least method and url data it is not essential

Irrech
  • 1,277
  • 2
  • 13
  • 18