Skip to content

Instantly share code, notes, and snippets.

@shanehou
Created May 27, 2016 15:05
Show Gist options
  • Save shanehou/2da6a7b03bd31357f1dee663f153e2b4 to your computer and use it in GitHub Desktop.
Save shanehou/2da6a7b03bd31357f1dee663f153e2b4 to your computer and use it in GitHub Desktop.
react-async-script example
import React from 'react'
import ReactDOM from 'react-dom'
import makeAsyncScriptLoader from "react-async-script"
class App extends React.Component {
appendPre(message) {
const pre = document.getElementById('output')
const textContent = document.createTextNode(message + '\n')
pre.appendChild(textContent)
}
listFiles() {
let request = gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
})
request.execute((resp) => {
appendPre('Files:')
const files = resp.files;
if (files && files.length > 0) {
for (let i = 0; i < files.length; i++) {
const file = files[i]
appendPre(file.name + ' (' + file.id + ')')
}
} else {
appendPre('No files found.')
}
})
}
loadDriveApi() {
gapi.client.load('drive', 'v3', this.listFiles)
}
handleAuthResult(authResult) {
const authorizeDiv = document.getElementById('authorize-div')
if (authResult && !authResult.error) {
authorizeDiv.style.display = 'none'
loadDriveApi()
} else {
authorizeDiv.style.display = 'inline'
}
}
checkAuth() {
console.log("Check Auth")
gapi.auth.authorize({
'client_id': this.props.clientID,
'scope': this.props.scopes.join(' '),
'immediate': true
}, this.handleAuthResult)
}
handleAuthClick(event) {
event.preventDefault()
console.log("Auth Click")
gapi.auth.authorize({client_id: this.props.clientID, scope: this.props.scopes, immediate: false}, this.handleAuthResult)
}
render() {
return (
<div>
<div id="authorize-div">
<span>Authorize access to Drive API</span>
<button id="authorize-button" onClick={e=>this.handleAuthClick(e)}>
Authorize
</button>
</div>
<pre id="output"></pre>
</div>
)
}
}
const callback = 'checkAuth'
let AppWrapper = makeAsyncScriptLoader(App, 'https://apis.google.com/js/client.js?onload=${callback}', {
callbackName: callback,
globalName: 'gapi'
})
const CLIENT_ID = 'my-client-id'
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
const onLoad = () => {
console.log("Loaded!")
}
ReactDOM.render(<AppWrapper asyncScriptOnload={onLoad} clientID={CLIENT_ID} scopes={SCOPES} />, document.getElementById('root'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment