Meteo HTTP call: can't access data

I’m experiencing a strange problem with meteor. I’m trying to make HTTP call an use the data in a React-Component. But I can’t access the returned data.
on the server:

'get': function get() {

    try {
      const data = Meteor.http.get('url', {
        params: {
            "api_key": "key",
            "attribute": "attribute"
        }
      }
      return data;

    } catch (exception) {
      throw new Meteor.Error('500', exception);
    }
},

on the client: i’ve set up a container using withTracker() so that i can access the http response as props in my react component.

export default withTracker(() => {
    var data = [];
    Meteor.call('get', function(error, success) { 
        if (error) { 
            console.log('error', error.reason); 
        } 
        if (success) { 
            data.push(success);
            console.log('success', success); 
        } 
    });

    return {
        data,
    };
})(Component);

I’ve tried all possible combination. Using arrays and objects, but none of them worked out. When using console.log(data), I get some data on the client. But using console.log(data[0]) return undefined.

I’ve also tried returning an object from the server 'get' method. An using js Object.assign. But when calling console.log(data.name) for example, I get undefined on the client.

Maybe I’m not solving it the right way, but I don’t understand why this is always returning undefined when I tried to access the object’s data.

Don’t place Meteor.call() inside withTracker.

withTracker only works with reactive sources, which Meteor.call() isn’t.

Instead, put the Meteor.call() inside a regular component method and call another component method as the callback.

class MyComponent extends React.Component {
  ...
  getData() {
    ...
    Meteor.call('myMethod', options, this.processData);
  }
  processData(error, result) {
    ... do something with the result ...
  }
  ...
}

And don’t forget to bind processData to this in your constructor, if you need to access props or state.

(Things would be a bit easier if Meteor.call() would support promises or async / await.)

1 Like

@waldgeist Thanks a lot. You made my day. I was searching for a solution to this four hours. I also tried using promise but this is a far the best solution. :+1::+1: