useSignOut
Description
This hook returns a signOut
function that can be used to sign the user out of Google Analytics via the Google Analytics Embed API.
Usage
import { signOut } from "react-use-analytics-api";
In your function component:
const signOut = useSignOut(gapi);
Provide the hook with gapi
, the Google Analytics Embed API. Call signOut
to sign the user out.
Signature
useSignOut(gapi?: GoogleAnalyticsEmbedAPI) => (() => void)
Arguments
Argument | Type | Description |
---|---|---|
gapi | GoogleAnalyticsEmbedAPI | undefined | The Google Analytics Embed API. When undefined , calling signOut does nothing. |
Return
The hook returns a function, signOut
.
signOut() => void
When gapi
is not undefined
, this function calls gapi.auth.signOut
to sign the user out of Google Analytics.
Example
import * as React from "react";import {useAnalyticsApi,useAuthorize,useSignOut,} from "react-use-analytics-api";export function UseSignOutExample(props) {const { ready, gapi, authorized, error } = useAnalyticsApi();const authorize = useAuthorize(gapi, {clientId,container: "authorize-container-id",});const signOut = useSignOut(gapi);// Workaround for API limitationconst [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>);}