mini
mini

Reputation: 199

Meteor: trigger template.event to call an external server with react in blaze template

I have to add a react component to a Meteor app (react in a blaze component) (Meteor Guide), to make it simple the component is a button that should trigger the events to send the input to a different server. If I try to make the http call from the client but I get the cross-origin error. Therefore I need to make the API call from the meteor server.

The flow of the request should be this:

Button clicked -> trigger template events -> Meteor.call('HTTPRequest', POST, url, data) -> save response in Meteor Mongo db and send to the react redux store

The problem I encountered is that I don't find a way to trigger the event from the react application.

Client side: The following file are frontend.

React App:

import React from 'react';

const App = () => {
    return <button onClick={...trigger the event...}> Run </button>
};

export default App;

Meteor file test.html:

<template name="test">
        <div>{{> React component=App onClick=onClick}}</div>
</template>

Meteor test.js

import App from './App.js';

Template.test.helpers({
    App() {
        return App;
    },
});

Template.test.events({
    'click send-code': (url, data) => {
       Meteor.call('HTTPRequest', 'POST', url, data);
    },
});

Server side:

runner.js

import { HTTP } from 'meteor/http';

Meteor.methods({
    'HTTPRequest'(method, url, data) {
        return new Promise((resolve, reject) => {
            try {
                HTTP.call(method, url, data || {}, (error, result) => {
                    if (error) {
                        reject(error);
                        return;
                    }
                    resolve(result);
                });

            } catch (e) {
                reject(e);
            }
        });
    }
});

Is there a way to call the server-side method (runner.js) directly from the react part?

If no how can I trigger the event to call the server method from react?

How can I pass data from react component to the Api call and save it back?

Thank you!

Upvotes: 1

Views: 171

Answers (1)

Mikkel
Mikkel

Reputation: 7777

It looks like you are expecting your blaze helpers to work with a react component, but it doesn't work like that.

You need to put the handler inside the React component. Quite simple really, something like this:

const App = () => {
    const clickHandler = () => {
         const data = {...}
         Meteor.call('HTTPRequest', 'POST', 'https://...', data);
    }
    return <button onClick={clickHandler}> Run </button>
};

This code isn't complete, you need to provide url and data, and do try/catch around it etc, but it demonstrates how to do it.

Upvotes: 1

Related Questions