Simon Breton Simon Breton - 3 months ago 8
Node.js Question

How do I pass value from my react component to my express API calls ?

I'm not really sure how I should ask about that. I've an app with React/Redux/d3 on the client-side and Node/express on the server side (correct me is this description seems wrong). I would like to allow users to update the API client with for example a dropdown menu. I'm not looking for specific code here but more general pattern.

For exemple here is a part of my google analytics API call :

// query the data
var queryData = function(req, res) {
// authorize the client (see code above)
authorize(function() {
// do the actual call to the google api
analytics.data.ga.get({
'auth': jwtClient,
'ids': VIEW_ID,
'metrics': 'ga:uniquePageviews',
'dimensions': 'ga:pagePath',
'start-date': '30daysAgo',
'end-date': 'yesterday',
'sort': '-ga:uniquePageviews',
'max-results': 10,
}, function (err, response) {
if (err) {
console.log(err);
return;
}
// send the data to the client (i.e. browser)
res.send(response);
});
});
}

module.exports = {
queryData
};


Following the code above, I would like to have a drop-down menu with various
'start-date'
for example. Does my question is clear ? How do I do this ?

Answer

Your expressjs function can get request parameters from the request object "req"

 req.params.startDate

So you need to request your expressjs endpoint with the parameters need to make the code below variable and use the dynamic values.

 // query the data
 var queryData = function(req, res) {

    // req.params contains the parameters from the call to this expressjs function
    // Lets assume you send a "startDate" parameter
    var startDate = req.params.startDate

    // authorize the client (see code above)
    authorize(function() {
    // do the actual call to the google api
    analytics.data.ga.get({
      'auth': jwtClient,
      'ids': VIEW_ID,
      'metrics': 'ga:uniquePageviews',
      'dimensions': 'ga:pagePath',
      'start-date': startDate,         // Then use the parameter here
      'end-date': 'yesterday',
      'sort': '-ga:uniquePageviews',
      'max-results': 10,
    }, function (err, response) {
      if (err) {
        console.log(err);
        return;
      }
      // send the data to the client (i.e. browser)
      res.send(response);
    }); 
  });
}