How To use Meteor.calls return value and display in React?

I am trying to use Meteor.Call to call a server function , which returns a value and i want to display it.

I have the following code

return items.map((item) => {
        return (
          <tr key={item.SerialNumber}>
               <td>{item.SerialNumber}</td>
               {(() => {

                if (item.warehouse) {
                  Meteor.call("Warehouseread", item.warehouse, { fields: { name: 1 } }, (err, data) => {
                    if(err) console.log("Warehouseread.err",err)
                    warehouse = data.name; // >>>>>want to display this value
                    return
                }
              })()}</td>
......

I am calling a server function which returns data, and i want to extract data.name and display in the row.

The above method doesnot work , and i am looking for any solution to get achieve this.

Any suggestion is much appreciated !

Hello!

Yeah, that will not work for sure. Not only will this meteor call be run every time you render (bad!), but you are mixing data loading and rendering, which will be very confusing.

What you want to do is something like this:

class ItemComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
        data: null,
        error: null
    };
  }
  componentDidMount() {
    const { warehouse } = this.props;
    Meteor.call("Warehouseread", warehouse, { fields: { name: 1 } }, (err, data) => {
       if(err) return this.setState({ error: err.message });
       return this.setState({ data });
    });
  }
  render() {
    const { data, error } = this.state;

    if (error) return <td>{error}</td>;

    return <td>{data ? data.name : "Loading warehouse.."}</td>
  }
}

class ItemList extends Component {
  render() {
    const { items } = this.props;

    return items.map((item) => (
          <tr key={item.SerialNumber}>
            <td>{item.SerialNumber}</td>
            {item.warehouse && (
               <WarehouseInfo warehouse={item.warehouse} />
            )}
        </tr>
    ));
}

This code probably has some syntax errors, I just wrote it in this this forum, but I hope you get the gist of keeping rendering away from meteor methods.

We still have some way to go though, as this will result in calling a meteor method for EVERY item, which can be very bad if you have a lot of items.

If I were you, I would load the warehouses as along with the items ahead of time, and then search through the warehouse list to display the right warehouse for each item. Alternatively you do this already on the server, populating the warehouse fields before sending it to the client (if you load the items though a method that is)

2 Likes

I was actually planning of using this! Thanks a lot !! Cheers