Load async YouTube API in to ReactJS application - google-api

I need to load the YouTube JavaScript API which requires you to include a script tag with an onload query string which points towards a global callback function. Once the Google client is loaded the callback gets called:
<script>
function init() {
gapi.client.setApiKey('465723722VeAji1ZVqYiJxB7oyMTVLI');
gapi.client.load('youtube', 'v3', function() {
YouTubeClientLoaded = true;
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=init"></script>
This all works fine in principle but I'm having a hard time working out how to integrate this global callback in to my ReactJS application. How can I tell react that the client is loaded and ready to use?
I've had a few thoughts but all seem hacky. I thought about starting the React app up and setting a timer that periodically checks for the existence of the YouTubeClientLoaded global variable (or the gapi object) or perhaps a pubsub mechanism so my global init function can emit when it's ready. Problem with the pubsub route is that the pubsub itself would also need to be global so then how do I get that communicating with React...
Is there a more correct way of achieving this?

Related

Socket.IO client event handler not called?

I'm an iOS developer who recently started using Socket.IO. During the life cycle of my iOS application, my server will be receiving messages from my app as the client, but for one particular case, the server will also need to receive a message from a web browser as the client. I'm testing a very basic browser UI, which includes a text field and a button and on the tap of that button, a numeric code (which was entered in the text field) needs to be sent to the server. This is what that looks like:
<form>
Code:<br>
<input type="text" id="code" name="code"><br>
<input type="submit" id="validatebutton" value="Validate">
<script src="/socket.io-client/dist/socket.io.js"></script>
<script>
document.getElementById("validatebutton").onclick = function() {
var socket = io('http://localhost:3000');
socket.on('connect', function(clientSocket) {
clientSocket.emit('validateCode', document.getElementById("code"));
});
};
</script>
</form>
The connection works fine. When I run this code, the client successfully connects to the listening socket server. The only problem is that the event handler is not executed. I may be very off here, but what I went for is a client event handler, which is included in the Swift SDK:
self.socket.on(clientEvent: .connect, callback: { (data:[Any], ack:SocketAckEmitter) in
// Do something here
})
self.socket.connect()
I'm just assuming that the Javascript client has a client event handler (named 'connect') as well, which is received by the client at the moment of connecting to a server. Like I said, I may be way off here. I'm just following the Socket.IO documentation posted on their website, which tells me to do it this way. If someone can tell me what I'm missing, or what I'm doing wrong, it would be much appreciated. Sorry for all the noobishness, but I really don't know where else to turn, since the official documentation is very vague and the other question on Stack are a little too advanced for me.
I wouldn't put the emit function inside the connect. Try emitting like below in your client
<script>
var socket = io('http://localhost:3000');
document.getElementById("validatebutton").onclick = function() {
socket.emit('validateCode', document.getElementById("code"));
};
</script>
Your click event was probably getting executed, but the emit was not due to it being wrapped in the connect function (which only gets executed when the socket connects to the server)
Also I would put the JavaScript in its own file, but for now, at least after the form (not inside it) will work.

React + Redux & initial request configuration

I'm working on React+Redux application and i stuck with some app initialization problems, so i wanna ask:
How to make initial setup for application, e.g. where to set default request headers for communication with api?
Lets assume i have some requestManager module which is not react component.
And it's king of proxy, it adds proper headers for every request.
But in case of user log out and log in i need to set proper token in header.
How to accomplish that?
Can not-react component listen for store events?
What are best practices for that?
Are there some good examples?
It you are using webpack. It has Define plugin which you can declare once and use in every .js file anytime
if you have not experience with webpack
https://github.com/petehunt/webpack-howto#6-feature-flags
In webpack configuration.
var definePlugin = new webpack.DefinePlugin({
'process.env': {
"NODE_ENV": JSON.stringify("development"),
"API_HOST": "localhost:3001",
"API_TOKEN": "my-token"
}
})
In js file
if (process.env.NODE_ENV) { // Yep, just call like that
//Whatever
console.log(process.env.API_TOKEN) // print out "my-token"
}

Railo Custom 505 handler and ajax pathing

I have an external javascript file that calls a setinterval function that checks a cfc for file transfer completion between server and a remote computer. When I call this function with standard error handler it works. Soon as I add the custom error handler it fails. Im dumb founded.
File_transfer.js
{
Function check_stream_server ()
Ajax call to query, application scoped, query-object.
Path = "ss_check.cfc"
};
// exception log and response with custom error
// I work with no custom error handler
Function send_file ()
{
Ajax to Put file in object; // I work
Same ajax call to Start stream.
thread if not running; //I work
Setinterval (check_stream_server, 5000) //I set interval
}
}
}
Index.cfm null {
Include the file_transfer.js
<button>click </button>
<script>
Button.on ('click', function (){
Send_file()
})
</script>
}
Index.cfm, check_ss.cfc, and the object_insert.cfc are all in same folder. Js is in external lib folder.
Sorry that this code sucks but I'm typing this from phone and won't be able to sleep tonight or be dreaming about it all night.
If it helps I'm also running a compiled archive.
It was a bug in setting the cf admin on update error. There was a remote clients = arrayofclients that was not removed from someone copying and pasting the example in the docs. I had a work around that worked by initializing the functions into the proper scopes in the initial cfm page, but later found out it was a bug when setting the custom error handler

Use gapi.client javascript to execute my custom Google API

I have a service that is successfully deployed to Google Endpoints and it is accessible through browser.
Now I am trying to load Google API javascript client library to call my services using javascript.
As far as I know, I should do this
gapi.client.load([MY_APP_NAME], 'v1', function() {
var request = gapi.client.[API_NAME].[SERVICE_NAME].[METHOD]();
request.execute(function(jsonResp, rawResp) {...});
);
But I always get an exception at run time complaining about gapi.client.[MY_API_NAME] is undefined. I do the same thing with any Google API (such as Plus) and it works fine. For example, If I load 'plus' API, I will have access to gapi.client.plus... and I can call methods.
Am I missing something? All samples and documents are about Google Service APIs and I could not find a sample for custom APIs (the one that developers write).
I even tried gapi.client.request with different paths (absolute path and relative path) but I get 404 - Not Found error in "status".
var request = gapi.client.request({'path':
'https://[APP_NAME].appspot.com/_ah/api/[SERVICE_NAME]/v1/[METHOD]'
, 'method': 'GET'});
request.execute(function(jsonResp, rawResp) {...});
var request = gapi.client.request({
'path':'/[SERVICE_NAME]/v1/[METHOD]',
'method': 'GET'});
request.execute(function(jsonResp, rawResp) {...});
The problem was a missing parameter in calling gapi.client.load().
I looked at the definition of gapi.client.load at this link https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientload
gapi.client.load(name, version, callback)
which then later I found out is not totally correct and an optional parameter is missing (app_api_root_url).
gapi.client.load(name, version, callback, app_api_root_url)
If the app_api_root_url is missing, the client is loaded for Google Service APIs only (app_api_root_url such as https://myapp.appspot.com/_ah/api)
You can find more details on how to use gapi.client.load() properly at this link https://developers.google.com/appengine/docs/java/endpoints/consume_js
As you can see in the following piece of code, I didn't have ROOT parameter when I was calling gapi.client.load and that is why Google by default was looking at its own service API and obviously could not find my APIs.
var ROOT = 'https://your_app_id.appspot.com/_ah/api';
gapi.client.load('your_api_name', 'v1', function() {
var request = gapi.client.your_api_name.your_method_name();
request.execute(function(jsonResp, rawResp) {
//do the rest of what you need to do
});
}, ROOT);
NOTE: your_app_id is used in ROOT parameter only to load the client script. After loading is done, you will have an object that is named after your API and not your app. That object is like your Java (service) class and you can use to invoke methods directly.

Flex BlazeDS detect browser close

I have a Flex application that connects to a BlazeDS server using the StreamingAMF channel. I want to detect on the server side in case the browser is closed. I have added an implementation for FlexClientListener & registered it to the FlexClient (FlexContext.getFlexClient().addClientDestroyedListener)
But the clientDestroyed method of Listener is not invoked on browser close. It gets invoked on Session timeout. Is there any other way to achieve this?
You won't be able to detect browser interactions on a client from the server.
Your best guess is to make use of ExternalInterface. It allows your Flash app to communicate with JavaScript, and vice versa.
Use the JavaScript onClose event to trigger some JavaScript which will call a function in your Flash App which will make a remote call to let your server side know that the browser is being closed.
We too had similar issue, not closing the session was causing memory leak in BlazeDS, We wrote the below script in swf wrapper javascript, to make ensure that closing browser invokes session closure code in flex
<script language="JavaScript" type="text/javascript">
function cleanup()
{
getMyApplication("swf_filename_without_extension").cleanUp();
alert("Disconnected! Press OK to continue.");
}
function getMyApplication(appName)
{
if (navigator.appName.indexOf ("Microsoft") != -1)
{
return window[appName];
}
else
{
return document[appName];
}
}
</script>
<body onbeforeunload="cleanup()">
In Flex add a call back on creation complete listener
ExternalInterface.addCallback("cleanUp",cleanUp);
and write all your session closure code in cleanUp method.
Note: don't forget to put the alert message in javascript. That will give enough time for cleanUp method to execute.

Resources