React Use Analytics API
Edit page
Home
Hooks
useAnalyticsApiuseAuthorizeDescriptionUsageSignatureExampleManually Synchronizing HooksuseDatauseDataChartuseSignOutuseViewSelector
Code of ConductMIT License

useAuthorize

Description

The useAuthorize hook can be used to authorize the user via the Google Analytics Embed API in several ways:

  • Render an authorize button using a Client ID
  • Authorize with an access token

The user must be authorized before the API can query for things like chart data.

Usage

import { useAuthorize } from "react-use-analytics-api";

The useAuthorize hook returns an authorize function that calls gapi.auth.authorize using the provided auth options.

Using A Client ID

const authorize = useAuthorize(gapi, {
clientId:
"1234567890123-abc123def456ghi789jkl012mno345pq.apps.googleusercontent.com",
container: "authorize-container-id",
});

Call authorize to render an authorize button (when signed out) and sign-in information (when signed in) into the container with that ID. The button can be used to authorize the user.

If the user is already authorized and reloads the page, they will be signed in immediately when calling authorize.

The contents of the container are not managed by React, so be sure to leave it empty and not to do anything to trigger a render on that container.

Limitations

Google's API doesn't render the authorize button more than once per page load. Be sure to take this into consideration.

A novel approach is used in the example below to detect whether the container is empty and prompt the user to refresh the page.

Using An Access Token

const authorize = useAuthorize(gapi, {
serverAuth: {
access_token: "ACCESS_TOKEN_GOES_HERE",
},
});

Call authorize to authorize using the access token provided.

Signature

useAuthorize( gapi: GoogleAnalyticsEmbedAPI | undefined, options: AuthorizeOptions, onSignIn?: () => void ) => (() => void)

Arguments

ArgumentTypeDescription
gapiGoogleAnalyticsEmbedAPI | undefinedThe Google Analytics Embed API. When undefined, calling authorize does nothing.
optionsAuthorizeOptionsThe options for the authorization.
onSignIn() => voidCalled on a successful sign-in. You can use this to do things like change the view on auth success.

Return

The hook returns a function, authorize.

authorize() => void

When gapi is not undefined, this function calls gapi.auth.authorize using the provided auth options.

Example

The following example demonstrates use of the useAuthorize hook with a Client ID to sign a user into Google Analytics.

Due to an API limitation, the authorize button can only be rendered to the page once per page load. This means once the container div is destroyed and re-rendered by React, the authorize button will no longer appear.

To see this happening, use the sidebar to navigate to another page on this site (which doesn't trigger a full page reload), then come back to this one. The API will no longer render the authorize button in the example below.

To take this into consideration, we use a ref to check if the authorize container has any contents after authorize is called. If it's empty when it shouldn't be, we show a prompt to refresh the page. You can replace this with a button that performs a refresh, if you'd like.

import * as React from "react";
import {
useAnalyticsApi,
useAuthorize,
useSignOut,
} from "react-use-analytics-api";
export function UseAuthorizeExample(props) {
const { ready, gapi, authorized, error } = useAnalyticsApi();
const authorize = useAuthorize(gapi, {
clientId,
container: "authorize-container-id",
});
const signOut = useSignOut(gapi);
// Workaround for API limitation
const [authorizeCalled, setAuthorizeCalled] = React.useState(false);
const authDiv = React.useRef(null);
const hasAuthElements =
authDiv.current && authDiv?.current?.children?.length > 0;
React.useEffect(() => {
if (ready && !error && !authorizeCalled) {
authorize();
setAuthorizeCalled(true);
}
}, [authorize, authorizeCalled, error, ready]);
return (
<div>
{!error &&
(ready && !!gapi ? (
<div>
{authorized && (
<div>
☀️ Logged into Google Analytics!{" "}
<button onClick={() => signOut()}>Sign Out</button>
</div>
)}
{!authorized && <div>🔐 Not logged into Google Analytics</div>}
<div id="authorize-container-id" ref={authDiv} />
{!authorized && authorizeCalled && !hasAuthElements && (
<div>🔄 Refresh the page to access analytics.</div>
)}
</div>
) : (
<div>⌛ Loading...</div>
))}
{error && <div>{error.toString()}</div>}
</div>
);
}

Manually Synchronizing Hooks

If you authorize or sign out manually outside of this library (and React), you will want to synchronize any hooks you have instantiated so they're aware of your new authorization status.

To do this, you can access the emitter and singleton used by the hooks in this library:

import { apiStateEmitter, apiSingleton } from "react-use-analytics-api";

Then, when your auth state changes, you can manually update the hooks via the authorized event:

apiSingleton.authorized = isAuthorized;
apiStateEmitter.emit("authorized", isAuthorized);

This will update the authorized state for all existing hooks as well as any new hooks instantiated thereafter.

You don't need to worry about this if you use the useAuthorize and useSignOut hooks, since they do this for you automatically.