Open IanBoyte opened 2 years ago
import { useEffect } from 'react';
import useDrivePicker from 'react-google-drive-picker'
function App() {
const [openPicker, authResponse] = useDrivePicker();
const handleOpenPicker = () => {
let config: PickerConfiguration = {
clientId: clientId,
developerKey: developerKey,
viewId: "DOCS",
viewMimeTypes: mimeTypes,
showUploadView: true,
showUploadFolders: true,
supportDrives: true,
multiselect: props.multiselect,
customScopes: ['https://www.googleapis.com/auth/drive.file'],
callbackFunction: handleGoogleDrive,
};
const defaultScopes = ['https://www.googleapis.com/auth/drive.readonly'];
const client = google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: (config.customScopes
? [...defaultScopes, ...config.customScopes]
: defaultScopes
).join(' '),
callback: (tokenResponse: authResult) => {
console.log(tokenResponse);
config.token = tokenResponse.access_token;
openPicker(config);
},
})
client.requestAccessToken()
}
return (
<div>
<button onClick={() => handleOpenPicker()}>Open Picker</button>
</div>
);
}
export default App;
The library initializes a global variable "google" that can be used to get an access token.
how to get refresh token @Mykola-Veryha ?
how to get refresh token
In this callback you can get the refresh tocken: tokenResponse.access_token Just save it to State and use where you need
callback: (tokenResponse: authResult) => {
console.log(tokenResponse);
config.token = tokenResponse.access_token;
openPicker(config);
},
Why is the hook returning authResponse
if it's going to stay undefined / we won't be able to use it?
In my case it's only accessible after the current page I'm working on hot-reloads.
The library initializes a global variable "google" that can be used to get an access token.
how to import the google variable?
I realized that authResponse
does return an access_token
. But, it is undefined when we try to access it in the callback function.
To solve this you can do the following in your React component:
const [openPicker, authResponse] = useDrivePicker();
const { access_token } = authResponse || {};
let token = useRef<string | undefined>(undefined);
useEffect(() => {
if (access_token !== undefined) {
token.current = access_token;
}
}, [access_token]);
Now, you can access token.current
in your component.
authResponse
is always undefined.