### Jest Mock Setup Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Instructions and examples for setting up Jest mocks for the Google Sign-In library, including importing the mock and using provided mock data. ```APIDOC ## Jest Mock Setup ### Description The library ships a ready-to-use Jest mock at `@react-native-google-signin/google-signin/jest/build/setup`. Import it in your Jest setup file to avoid native module resolution errors in tests. ### Setup ```ts // jest.config.js module.exports = { preset: 'react-native', setupFiles: ['@react-native-google-signin/google-signin/jest/build/setup'], }; // ---- In your test file ---- import { GoogleSignin, statusCodes, isErrorWithCode, } from '@react-native-google-signin/google-signin'; // mockUserInfo and mockGoogleSignInResponse are also exported for convenience import { mockUserInfo, mockGoogleSignInResponse, } from '@react-native-google-signin/google-signin/jest/build/setup'; describe('Auth flow', () => { it('signs in successfully', async () => { const response = await GoogleSignin.signIn(); expect(response).toStrictEqual(mockGoogleSignInResponse); // { type: 'success', data: { user: { email: 'mockEmail', ... }, idToken: 'mockIdToken', ... } } }); it('returns current user synchronously', () => { expect(GoogleSignin.getCurrentUser()).toStrictEqual(mockUserInfo); }); it('reports correct status codes', () => { expect(statusCodes.SIGN_IN_CANCELLED).toBe('mock_SIGN_IN_CANCELLED'); expect(statusCodes.IN_PROGRESS).toBe('mock_IN_PROGRESS'); }); }); ``` ``` -------------------------------- ### Jest Mock Setup for Google Sign-In Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Integrate the provided Jest mock by importing it in your Jest setup file to prevent native module resolution errors during tests. Mocked values for user info, sign-in responses, and status codes are exported for convenience. ```typescript // jest.config.js module.exports = { preset: 'react-native', setupFiles: ['@react-native-google-signin/google-signin/jest/build/setup'], }; // ---- In your test file ---- import { GoogleSignin, statusCodes, isErrorWithCode, } from '@react-native-google-signin/google-signin'; // mockUserInfo and mockGoogleSignInResponse are also exported for convenience import { mockUserInfo, mockGoogleSignInResponse, } from '@react-native-google-signin/google-signin/jest/build/setup'; describe('Auth flow', () => { it('signs in successfully', async () => { const response = await GoogleSignin.signIn(); expect(response).toStrictEqual(mockGoogleSignInResponse); // { type: 'success', data: { user: { email: 'mockEmail', ... }, idToken: 'mockIdToken', ... } } }); it('returns current user synchronously', () => { expect(GoogleSignin.getCurrentUser()).toStrictEqual(mockUserInfo); }); it('reports correct status codes', () => { expect(statusCodes.SIGN_IN_CANCELLED).toBe('mock_SIGN_IN_CANCELLED'); expect(statusCodes.IN_PROGRESS).toBe('mock_IN_PROGRESS'); }); }); ``` -------------------------------- ### Get Currently Signed-In User Synchronously Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Synchronously returns the cached `User` object for the currently signed-in user, or `null` if no user is signed in. This method does not perform any network requests. ```typescript import { GoogleSignin } from '@react-native-google-signin/google-signin'; function showUserName() { const user = GoogleSignin.getCurrentUser(); // Expected: User | null if (user) { console.log(`Hello, ${user.user.givenName}!`); console.log('Email:', user.user.email); console.log('Photo URL:', user.user.photo); } else { console.log('Not signed in'); } } ``` -------------------------------- ### Get Current User's Tokens Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Retrieves the current user's `idToken` and `accessToken` without initiating a new sign-in flow. Throws an error if no user is signed in. On Android, it refreshes the access token from the local cache. ```typescript import { GoogleSignin, isErrorWithCode } from '@react-native-google-signin/google-signin'; async function callGoogleApi() { try { const { idToken, accessToken } = await GoogleSignin.getTokens(); // Expected: { idToken: 'eyJh...', accessToken: 'ya29...' } const response = await fetch( 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json', { headers: { Authorization: `Bearer ${accessToken}` } }, ); const profile = await response.json(); console.log(profile); } catch (error) { if (isErrorWithCode(error)) { console.error('Token error:', error.code, error.message); } } } ``` -------------------------------- ### GoogleSignin.configure(options) Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Initialises the native Google Sign-In SDK. This method must be called before any other GoogleSignin method. It accepts an options object to customize the sign-in flow, including web client ID, scopes, and more. ```APIDOC ## GoogleSignin.configure(options) ### Description Initialises the native Google Sign-In SDK. Must be called before any other `GoogleSignin` method — typically in `componentDidMount` or `useEffect` at app startup. Throws synchronously if `offlineAccess` is `true` but no `webClientId` is provided. ### Parameters #### Options - **webClientId** (string) - Required - Google Cloud project's Web client ID. Required for offline access. - **iosClientId** (string) - Optional - iOS specific client ID. Alternative to configuring via `GoogleService-Info.plist`. - **offlineAccess** (boolean) - Optional - If `true`, requests a server auth code for backend token exchange. Defaults to `false`. - **hostedDomain** (string) - Optional - Restricts sign-in to users with the specified domain. - **scopes** (Array) - Optional - An array of OAuth scopes to request. Defaults to email and profile scopes. - **profileImageSize** (number) - Optional - iOS only. The desired size for the user's profile image. Defaults to 120. ### Request Example ```javascript import { GoogleSignin } from '@react-native-google-signin/google-signin'; GoogleSignin.configure({ webClientId: '123456789-abc.apps.googleusercontent.com', iosClientId: '123456789-ios.apps.googleusercontent.com', offlineAccess: true, hostedDomain: 'mycompany.com', scopes: [ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/calendar', ], profileImageSize: 150, }); ``` ``` -------------------------------- ### Configure Google Sign-In Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Initializes the native Google Sign-In SDK. Must be called before any other GoogleSignin method. Configure options like webClientId, iosClientId, offlineAccess, hostedDomain, scopes, and profileImageSize. ```typescript import { GoogleSignin } from '@react-native-google-signin/google-signin'; // Basic setup (email + profile scopes by default) GoogleSignin.configure({ webClientId: '123456789-abc.apps.googleusercontent.com', // required for offline access iosClientId: '123456789-ios.apps.googleusercontent.com', // iOS only, alternative to plist offlineAccess: true, // request server auth code for backend token exchange hostedDomain: 'mycompany.com', // restrict sign-in to this domain scopes: [ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/calendar', ], profileImageSize: 150, // iOS only, default 120 }); ``` -------------------------------- ### GoogleSignin.signIn(options?) Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Initiates the interactive Google Sign-In flow. This method returns a discriminated union indicating success or cancellation. Errors other than cancellation are thrown and should be handled with a try-catch block. ```APIDOC ## GoogleSignin.signIn(options?) ### Description Triggers the interactive Google Sign-In flow. Returns a discriminated union: `{ type: 'success', data: User }` or `{ type: 'cancelled', data: null }`. Non-cancellation errors are thrown and must be caught separately. ### Parameters #### Options - **loginHint** (string) - Optional - iOS only. Pre-fills the email address in the sign-in prompt. ### Response #### Success Response - **type** (string) - Always 'success'. - **data** (object) - Contains user information and tokens. - **user** (object) - User details (id, name, email, photo, etc.). - **idToken** (string) - The Google ID token. - **serverAuthCode** (string) - The server authorization code for backend token exchange (if `offlineAccess` was enabled). #### Cancelled Response - **type** (string) - Always 'cancelled'. - **data** (null) - Always null. ### Request Example ```javascript import { GoogleSignin, isSuccessResponse, isCancelledResponse, isErrorWithCode, statusCodes, } from '@react-native-google-signin/google-signin'; async function signIn() { try { await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); const response = await GoogleSignin.signIn({ loginHint: 'user@example.com', }); if (isSuccessResponse(response)) { const { user, idToken, serverAuthCode } = response.data; console.log('Signed in as', user.name, user.email); console.log('ID Token:', idToken); console.log('Server auth code (for backend):', serverAuthCode); } else if (isCancelledResponse(response)) { console.log('User cancelled sign-in'); } } catch (error) { if (isErrorWithCode(error)) { switch (error.code) { case statusCodes.IN_PROGRESS: console.warn('Sign-in already in progress'); break; case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: console.error('Play Services unavailable (Android)'); break; default: console.error('Sign-in error:', error.message, error.code); } } } } ``` ``` -------------------------------- ### Expo Dynamic Config Plugin for Google Sign-In Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Configure the Google Sign-In Expo plugin dynamically in `app.config.ts` by providing the `iosUrlScheme` within the plugins array. ```typescript // app.config.ts (dynamic config) import { ExpoConfig } from 'expo/config'; const config: ExpoConfig = { name: 'MyApp', slug: 'my-app', plugins: [ [ '@react-native-google-signin/google-signin', { iosUrlScheme: 'com.googleusercontent.apps.123456789-ios' }, ], ], }; export default config; ``` -------------------------------- ### Configuration File for Web Client ID Source: https://github.com/react-native-google-signin/google-signin/blob/master/example/README.md Create this configuration file to store your web client ID. Ensure the 'webClientId' is replaced with your actual Google Cloud project's web client ID. ```typescript export default { webClientId: 'your-web-client-id.apps.googleusercontent.com', }; ``` -------------------------------- ### GoogleSigninButton Component Source: https://context7.com/react-native-google-signin/google-signin/llms.txt A native Google Sign-In button that automatically adapts to the system color scheme. It supports three sizes (Icon, Standard, Wide) and two color themes (Dark, Light). The default size is Standard (230x48 px). ```APIDOC ## GoogleSigninButton Component ### Description A native Google Sign-In button that automatically adapts to the system color scheme. Supports three sizes (`Icon`, `Standard`, `Wide`) and two color themes (`Dark`, `Light`). Size defaults to `Standard` (230×48 px). ### Props - **size** (GoogleSigninButton.Size) - Optional - The size of the button. Defaults to `GoogleSigninButton.Size.Standard`. - **color** (GoogleSigninButton.Color) - Optional - The color theme of the button. Defaults to the system's color scheme. - **onPress** (function) - Required - Callback function to be called when the button is pressed. - **disabled** (boolean) - Optional - Whether the button is disabled. - **accessibilityLabel** (string) - Optional - Accessibility label for the button. ### Usage Example ```tsx import React from 'react'; import { View } from 'react-native'; import { GoogleSigninButton, GoogleSignin } from '@react-native-google-signin/google-signin'; function SignInScreen() { const handleSignIn = async () => { await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); const response = await GoogleSignin.signIn(); if (isSuccessResponse(response)) { console.log('Signed in:', response.data.user.email); } }; return ( {/* Icon button — 48×48 px */} {/* Standard button — 230×48 px, auto color scheme */} {/* Wide button — 312×48 px */} ); } ``` ``` -------------------------------- ### Google Sign-In Button Component Source: https://context7.com/react-native-google-signin/google-signin/llms.txt The `GoogleSigninButton` component provides a native, adaptive button for Google Sign-In. It supports different sizes (Icon, Standard, Wide) and color themes (Dark, Light), automatically adapting to the system's color scheme. ```tsx import React from 'react'; import { View } from 'react-native'; import { GoogleSigninButton, GoogleSignin, isSuccessResponse, } from '@react-native-google-signin/google-signin'; function SignInScreen() { const handleSignIn = async () => { await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); const response = await GoogleSignin.signIn(); if (isSuccessResponse(response)) { console.log('Signed in:', response.data.user.email); } }; return ( {/* Icon button — 48×48 px */} {/* Standard button — 230×48 px, auto color scheme */} {/* Wide button — 312×48 px */} ); } ``` -------------------------------- ### Perform Google Sign-In Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Triggers the interactive Google Sign-In flow. Handles success, cancellation, and various error codes like IN_PROGRESS and PLAY_SERVICES_NOT_AVAILABLE. Returns a discriminated union for type-safe handling. ```typescript import { GoogleSignin, isSuccessResponse, isCancelledResponse, isErrorWithCode, statusCodes, } from '@react-native-google-signin/google-signin'; async function signIn() { try { await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); const response = await GoogleSignin.signIn({ loginHint: 'user@example.com', // iOS only: pre-fill email }); if (isSuccessResponse(response)) { const { user, idToken, serverAuthCode } = response.data; console.log('Signed in as', user.name, user.email); console.log('ID Token:', idToken); console.log('Server auth code (for backend):', serverAuthCode); // Expected: { type: 'success', data: { user: { id, name, email, photo, ... }, idToken, ... } } } else if (isCancelledResponse(response)) { console.log('User cancelled sign-in'); // Expected: { type: 'cancelled', data: null } } } catch (error) { if (isErrorWithCode(error)) { switch (error.code) { case statusCodes.IN_PROGRESS: console.warn('Sign-in already in progress'); break; case statusCodes.PLAY_SERVICES_NOT_AVAILABLE: console.error('Play Services unavailable (Android)'); break; default: console.error('Sign-in error:', error.message, error.code); } } } } ``` -------------------------------- ### GoogleSignin.signOut() Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Signs the current user out of the app. This action does not revoke permissions granted by the user. The method resolves with `null` upon successful sign-out. ```APIDOC ## `GoogleSignin.signOut()` ### Description Signs the current user out of the app. Does not revoke permissions. Resolves with `null`. ### Method `signOut()` ### Parameters None ### Response `null` on success. ### Request Example ```ts import { GoogleSignin } from '@react-native-google-signin/google-signin'; async function signOut() { try { await GoogleSignin.signOut(); console.log('User signed out'); } catch (error) { console.error('Sign-out error:', error); } } ``` ``` -------------------------------- ### GoogleSignin.hasPlayServices(options?) Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Checks if Google Play Services are available on the device. This is an Android-only check and always resolves to `true` on iOS. It's recommended to call this before `signIn` on Android to prompt the user to update if necessary. ```APIDOC ## GoogleSignin.hasPlayServices(options?) ### Description Checks that Google Play Services are available on the device (Android-only check; always resolves `true` on iOS). Should be called before `signIn` on Android to provide a user-friendly upgrade dialog. ### Parameters #### Options - **showPlayServicesUpdateDialog** (boolean) - Optional - If `true`, prompts the user to update Google Play Services if they are outdated. Defaults to `false`. ### Response #### Success Response - **available** (boolean) - Indicates whether Google Play Services are available. ### Request Example ```javascript import { GoogleSignin, isErrorWithCode, statusCodes, } from '@react-native-google-signin/google-signin'; async function checkPlayServices() { try { const available = await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true, }); console.log('Play Services available:', available); } catch (error) { if (isErrorWithCode(error) && error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) { console.error('Play Services not available'); } } } ``` ``` -------------------------------- ### GoogleSignin.addScopes(options) Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Requests additional OAuth scopes from the user at runtime. On iOS, if all requested scopes are already granted, the current user is returned immediately. On Android, a silent sign-in is performed after the user approves the new scopes to obtain a fully merged scope list. Returns `SignInResponse | null` if a user is currently signed in, otherwise `null`. ```APIDOC ## `GoogleSignin.addScopes(options)` ### Description Requests additional OAuth scopes from the user at runtime. On iOS, if all requested scopes are already granted the current user is returned immediately. On Android, a silent sign-in is performed after the user approves the new scopes to obtain a fully merged scope list. Returns `SignInResponse | null` (`null` if no user is currently signed in). ### Method `addScopes(options)` ### Parameters #### Request Body - **options** (object) - Required - An object containing the scopes to request. - **scopes** (array of strings) - Required - An array of OAuth scope strings. ### Response - `SignInResponse | null` - Returns `null` if no user is currently signed in. - Returns `SignInResponse` object on success, which includes the updated user data and scopes. ### Request Example ```ts import { GoogleSignin, isSuccessResponse } from '@react-native-google-signin/google-signin'; async function requestDriveAccess() { const response = await GoogleSignin.addScopes({ scopes: [ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/user.gender.read', ], }); if (!response) { console.log('No user signed in'); return; } if (isSuccessResponse(response)) { console.log('New scope list:', response.data.scopes); } else { console.log('User cancelled scope request'); } } ``` ``` -------------------------------- ### GoogleSignin.signInSilently() Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Attempts to restore a previously signed-in user without any UI interaction. Returns a success response with user data if a cached session is available, or a 'no saved credential' response if the user has never signed in or has signed out. ```APIDOC ## `GoogleSignin.signInSilently()` ### Description Attempts to restore a previously signed-in user without any UI interaction. Returns `{ type: 'success', data: User }` if a cached session is available, or `{ type: 'noSavedCredentialFound', data: null }` if the user has never signed in or has signed out. ### Method `signInSilently()` ### Parameters None ### Response - `SignInResponse` or `NoSavedCredentialResponse` - `type`: 'success' | 'noSavedCredentialFound' - `data`: `User` object if type is 'success', `null` otherwise. ### Request Example ```ts import { GoogleSignin, isSuccessResponse, isNoSavedCredentialFoundResponse, } from '@react-native-google-signin/google-signin'; async function restoreSession() { const response = await GoogleSignin.signInSilently(); if (isSuccessResponse(response)) { console.log('Restored session for', response.data.user.email); } else if (isNoSavedCredentialFoundResponse(response)) { console.log('No saved session — show sign-in button'); } } ``` ``` -------------------------------- ### GoogleSignin.hasPreviousSignIn() Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Synchronously returns true if a user was previously signed in during a past app session. This is useful to decide whether to call signInSilently() on startup. ```APIDOC ## GoogleSignin.hasPreviousSignIn() ### Description Synchronously returns `true` if a user was previously signed in during a past app session. Useful to decide whether to call `signInSilently()` on startup. ### Usage Example ```ts import { GoogleSignin } from '@react-native-google-signin/google-signin'; function shouldAttemptSilentSignIn(): boolean { const hasPrevious = GoogleSignin.hasPreviousSignIn(); console.log('Has previous sign-in:', hasPrevious); return hasPrevious; } if (shouldAttemptSilentSignIn()) { GoogleSignin.signInSilently().then((response) => { console.log('Silent sign-in result:', response.type); }); } ``` ``` -------------------------------- ### Check for Previous Google Sign-In Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Use `hasPreviousSignIn()` to synchronously check if a user has previously signed in. This is useful for determining if `signInSilently()` should be called on app startup. ```typescript import { GoogleSignin } from '@react-native-google-signin/google-signin'; function shouldAttemptSilentSignIn(): boolean { const hasPrevious = GoogleSignin.hasPreviousSignIn(); // Expected: boolean console.log('Has previous sign-in:', hasPrevious); return hasPrevious; } // Usage in startup logic if (shouldAttemptSilentSignIn()) { GoogleSignin.signInSilently().then((response) => { console.log('Silent sign-in result:', response.type); }); } ``` -------------------------------- ### Expo Config Plugin for Google Sign-In Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Add the Expo plugin to your `app.json` or `app.config.js` to automatically configure iOS URL schemes and Android OAuth client settings when using Expo's managed workflow and `expo prebuild`. ```json // app.json { "expo": { "plugins": [ [ "@react-native-google-signin/google-signin", { "iosUrlScheme": "com.googleusercontent.apps.YOUR_IOS_CLIENT_ID" } ] ] } } ``` -------------------------------- ### Expo Config Plugin Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Configuration for the Expo Config Plugin to automatically set up iOS URL schemes and Android OAuth client settings when using Expo's managed workflow. ```APIDOC ## Expo Config Plugin ### Description When using Expo managed workflow, add the plugin to `app.json` / `app.config.js` to automatically configure iOS URL schemes and Android OAuth client settings during `expo prebuild`. ### Configuration ```json // app.json { "expo": { "plugins": [ [ "@react-native-google-signin/google-signin", { "iosUrlScheme": "com.googleusercontent.apps.YOUR_IOS_CLIENT_ID" } ] ] } } ``` ```ts // app.config.ts (dynamic config) import { ExpoConfig } from 'expo/config'; const config: ExpoConfig = { name: 'MyApp', slug: 'my-app', plugins: [ [ '@react-native-google-signin/google-signin', { iosUrlScheme: 'com.googleusercontent.apps.123456789-ios' }, ], ], }; export default config; ``` ``` -------------------------------- ### Restore Previous Google Sign-In Session Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Attempts to restore a previously signed-in user without UI interaction. Use this on app startup to check for a cached session. It returns a success response with user data or indicates that no saved credential was found. ```typescript import { GoogleSignin, isSuccessResponse, isNoSavedCredentialFoundResponse, } from '@react-native-google-signin/google-signin'; async function restoreSession() { const response = await GoogleSignin.signInSilently(); if (isSuccessResponse(response)) { console.log('Restored session for', response.data.user.email); // { type: 'success', data: User } } else if (isNoSavedCredentialFoundResponse(response)) { console.log('No saved session — show sign-in button'); // { type: 'noSavedCredentialFound', data: null } } } // Typical usage on app startup async function componentDidMount() { GoogleSignin.configure({ webClientId: '...' }); await restoreSession(); } ``` -------------------------------- ### GoogleSignin.getCurrentUser() Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Synchronously returns the cached `User` object for the currently signed-in user, or `null` if no user is signed in. This method does not trigger any network requests. ```APIDOC ## `GoogleSignin.getCurrentUser()` ### Description Synchronously returns the cached `User` object for the currently signed-in user, or `null` if no user is signed in. Does not trigger any network request. ### Method `getCurrentUser()` ### Parameters None ### Response - `User | null` ### Request Example ```ts import { GoogleSignin } from '@react-native-google-signin/google-signin'; function showUserName() { const user = GoogleSignin.getCurrentUser(); // Expected: User | null if (user) { console.log(`Hello, ${user.user.givenName}!`); console.log('Email:', user.user.email); console.log('Photo URL:', user.user.photo); } else { console.log('Not signed in'); } } ``` ``` -------------------------------- ### Request Additional Google OAuth Scopes Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Requests additional OAuth scopes from the user at runtime. On Android, a silent sign-in is performed after approval to merge scopes. Returns the sign-in response or null if no user is signed in. ```typescript import { GoogleSignin, isSuccessResponse } from '@react-native-google-signin/google-signin'; async function requestDriveAccess() { const response = await GoogleSignin.addScopes({ scopes: [ 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/user.gender.read', ], }); if (!response) { console.log('No user signed in'); return; } if (isSuccessResponse(response)) { console.log('New scope list:', response.data.scopes); // User approved — make Drive API calls now } else { console.log('User cancelled scope request'); } } ``` -------------------------------- ### Handling Google Sign-In Status Codes Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Compare error codes against the `statusCodes` object after checking `isErrorWithCode(error)` to handle specific sign-in issues like cancellation, in-progress operations, or missing Google Play Services. ```ts import { statusCodes, isErrorWithCode, } from '@react-native-google-signin/google-signin'; // statusCodes shape: // { // SIGN_IN_CANCELLED: string, // user dismissed the sign-in dialog // IN_PROGRESS: string, // a sign-in operation is already running // PLAY_SERVICES_NOT_AVAILABLE: string, // Android only // SIGN_IN_REQUIRED: string, // silent sign-in failed, interactive required // NULL_PRESENTER: string, // iOS only: no presenting view controller // } try { await GoogleSignin.signIn(); } catch (error) { if (isErrorWithCode(error)) { if (error.code === statusCodes.IN_PROGRESS) { console.warn('Already signing in — debounce your button'); } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) { console.error('User needs to install/update Google Play Services'); } else if (error.code === statusCodes.NULL_PRESENTER) { console.error('iOS: no presenter view controller available'); } else { console.error('Unexpected sign-in error:', error.code, error.message); } } } ``` -------------------------------- ### Type Guards for Sign-In Responses Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Utilize `isSuccessResponse`, `isCancelledResponse`, and `isNoSavedCredentialFoundResponse` to discriminate union types for `SignInResponse` and `SignInSilentlyResponse`. This provides better TypeScript inference than direct `response.type` comparisons. ```typescript import { GoogleSignin, isSuccessResponse, isCancelledResponse, isNoSavedCredentialFoundResponse, } from '@react-native-google-signin/google-signin'; async function handleAuth() { // Interactive sign-in const signInResponse = await GoogleSignin.signIn(); if (isSuccessResponse(signInResponse)) { console.log(signInResponse.data.user.name); // TypeScript knows data is User } else if (isCancelledResponse(signInResponse)) { console.log('Cancelled'); // TypeScript knows data is null } // Silent sign-in const silentResponse = await GoogleSignin.signInSilently(); if (isSuccessResponse(silentResponse)) { console.log('Session restored for', silentResponse.data.user.email); } else if (isNoSavedCredentialFoundResponse(silentResponse)) { console.log('No previous session'); // TypeScript knows data is null } } ``` -------------------------------- ### statusCodes Source: https://context7.com/react-native-google-signin/google-signin/llms.txt A frozen object containing well-known error code strings thrown by the native module. These codes can be compared against `error.code` after checking `isErrorWithCode(error)`. ```APIDOC ## statusCodes ### Description A frozen object of well-known error code strings thrown by the native module. Compare against `error.code` after checking `isErrorWithCode(error)`. ### Error Codes - **SIGN_IN_CANCELLED**: User dismissed the sign-in dialog. - **IN_PROGRESS**: A sign-in operation is already running. - **PLAY_SERVICES_NOT_AVAILABLE**: Android only. Play services are not available. - **SIGN_IN_REQUIRED**: Silent sign-in failed, interactive sign-in is required. - **NULL_PRESENTER**: iOS only. No presenting view controller is available. ### Usage Example ```ts import { statusCodes, isErrorWithCode, } from '@react-native-google-signin/google-signin'; try { await GoogleSignin.signIn(); } catch (error) { if (isErrorWithCode(error)) { if (error.code === statusCodes.IN_PROGRESS) { console.warn('Already signing in — debounce your button'); } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) { console.error('User needs to install/update Google Play Services'); } else if (error.code === statusCodes.NULL_PRESENTER) { console.error('iOS: no presenter view controller available'); } else { console.error('Unexpected sign-in error:', error.code, error.message); } } } ``` ``` -------------------------------- ### Check Google Play Services Availability Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Checks if Google Play Services are available on the device (Android-only). Call this before signIn on Android to prompt users to update if necessary. Handles the PLAY_SERVICES_NOT_AVAILABLE error code. ```typescript import { GoogleSignin, isErrorWithCode, statusCodes, } from '@react-native-google-signin/google-signin'; async function checkPlayServices() { try { const available = await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true, // prompt user to update if outdated }); console.log('Play Services available:', available); // true } catch (error) { if (isErrorWithCode(error) && error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) { console.error('Play Services not available'); } } } ``` -------------------------------- ### isSuccessResponse / isCancelledResponse / isNoSavedCredentialFoundResponse Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Type-guard helper functions to narrow down the response type of sign-in operations. They provide better TypeScript inference compared to directly checking the 'type' property. ```APIDOC ## isSuccessResponse(response) / isCancelledResponse(response) / isNoSavedCredentialFoundResponse(response) ### Description Type-guard helpers that narrow a `SignInResponse` or `SignInSilentlyResponse` discriminated union to its specific variant. Equivalent to comparing `response.type` directly, but provide better TypeScript inference when used in if-statements. ### Usage ```ts import { GoogleSignin, isSuccessResponse, isCancelledResponse, isNoSavedCredentialFoundResponse, } from '@react-native-google-signin/google-signin'; async function handleAuth() { // Interactive sign-in const signInResponse = await GoogleSignin.signIn(); if (isSuccessResponse(signInResponse)) { console.log(signInResponse.data.user.name); // TypeScript knows data is User } else if (isCancelledResponse(signInResponse)) { console.log('Cancelled'); // TypeScript knows data is null } // Silent sign-in const silentResponse = await GoogleSignin.signInSilently(); if (isSuccessResponse(silentResponse)) { console.log('Session restored for', silentResponse.data.user.email); } else if (isNoSavedCredentialFoundResponse(silentResponse)) { console.log('No previous session'); // TypeScript knows data is null } } ``` ``` -------------------------------- ### GoogleSignin.revokeAccess() Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Disconnects the user's Google account from the app, revoking all granted permissions. This is useful for implementing a full "Delete my account" flow. The method resolves with `null`. ```APIDOC ## `GoogleSignin.revokeAccess()` ### Description Disconnects the user's Google account from the app, revoking all granted permissions. Useful for a full "Delete my account" flow. Resolves with `null`. ### Method `revokeAccess()` ### Parameters None ### Response `null` on success. ### Request Example ```ts import { GoogleSignin } from '@react-native-google-signin/google-signin'; async function deleteAccount() { try { await GoogleSignin.revokeAccess(); // revoke OAuth grants await GoogleSignin.signOut(); // clear local session console.log('Access revoked and user signed out'); } catch (error) { console.error('Revoke error:', error); } } ``` ``` -------------------------------- ### GoogleSignin.getTokens() Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Returns the current user's `idToken` and `accessToken` without triggering a new sign-in flow. Throws an error if no user is signed in. On Android, this method invalidates and refreshes the access token from the local cache. ```APIDOC ## `GoogleSignin.getTokens()` ### Description Returns the current user's `idToken` and `accessToken` without triggering a new sign-in flow. Throws if no user is signed in. On Android, invalidates and refreshes the access token from the local cache. ### Method `getTokens()` ### Parameters None ### Response - `{ idToken: string, accessToken: string }` ### Request Example ```ts import { GoogleSignin, isErrorWithCode } from '@react-native-google-signin/google-signin'; async function callGoogleApi() { try { const { idToken, accessToken } = await GoogleSignin.getTokens(); // Expected: { idToken: 'eyJh...', accessToken: 'ya29...' } const response = await fetch( 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json', { headers: { Authorization: `Bearer ${accessToken}` } }, ); const profile = await response.json(); console.log(profile); } catch (error) { if (isErrorWithCode(error)) { console.error('Token error:', error.code, error.message); } } } ``` ``` -------------------------------- ### Sign Out Current Google User Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Signs the current user out of the application. This action does not revoke any granted permissions. It's typically used when a user explicitly chooses to log out. ```typescript import { GoogleSignin } from '@react-native-google-signin/google-signin'; async function signOut() { try { await GoogleSignin.signOut(); console.log('User signed out'); // Update UI state — user is now null } catch (error) { console.error('Sign-out error:', error); } } ``` -------------------------------- ### Type Guard for NativeModuleError Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Use `isErrorWithCode` to safely narrow down unknown errors to `NativeModuleError` before accessing the `code` property. This prevents TypeScript errors without unsafe casting. ```typescript import { isErrorWithCode, } from '@react-native-google-signin/google-signin'; try { await GoogleSignin.getTokens(); } catch (error) { if (isErrorWithCode(error)) { // error is now typed as NativeModuleError — safe to access .code console.log('Error code:', error.code); console.log('Message:', error.message); } else { // not a GoogleSignIn error console.error('Unknown error:', error); } } ``` -------------------------------- ### Revoke Google Account Access and Sign Out Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Disconnects the user's Google account from the app, revoking all granted permissions. This is useful for a full 'Delete my account' flow. It first revokes OAuth grants and then clears the local session. ```typescript import { GoogleSignin } from '@react-native-google-signin/google-signin'; async function deleteAccount() { try { await GoogleSignin.revokeAccess(); // revoke OAuth grants await GoogleSignin.signOut(); // clear local session console.log('Access revoked and user signed out'); } catch (error) { console.error('Revoke error:', error); } } ``` -------------------------------- ### isErrorWithCode(error) Source: https://context7.com/react-native-google-signin/google-signin/llms.txt A TypeScript type-guard that checks if an error object has a 'code' property, indicating it's a NativeModuleError. This is useful for safely accessing error codes without type assertions. ```APIDOC ## isErrorWithCode(error) ### Description TypeScript type-guard that narrows an unknown caught value to `NativeModuleError` (i.e., an error with a `code` property). Use this before accessing `error.code` to satisfy TypeScript without unsafe `as` casting. ### Usage ```ts import { isErrorWithCode } from '@react-native-google-signin/google-signin'; try { await GoogleSignin.getTokens(); } catch (error) { if (isErrorWithCode(error)) { // error is now typed as NativeModuleError — safe to access .code console.log('Error code:', error.code); console.log('Message:', error.message); } else { // not a GoogleSignIn error console.error('Unknown error:', error); } } ``` ``` -------------------------------- ### GoogleSignin.clearCachedAccessToken(token) Source: https://context7.com/react-native-google-signin/google-signin/llms.txt Android only. Clears a specific access token from the local cache. This method is a no-op on iOS and returns null. It should be called when an access token is rejected by a Google API (HTTP 401), after which getTokens() should be called again to obtain a fresh token. ```APIDOC ## GoogleSignin.clearCachedAccessToken(token) ### Description Android only. Clears a specific access token from the local cache. No-op on iOS (returns `null`). Call this when an access token is rejected by a Google API (HTTP 401), then call `getTokens()` again to obtain a fresh token. ### Parameters #### Path Parameters - **token** (string) - Required - The access token to clear from the cache. ### Usage Example ```ts import { GoogleSignin } from '@react-native-google-signin/google-signin'; async function callApiWithRefresh() { let { accessToken } = await GoogleSignin.getTokens(); let response = await fetch('https://www.googleapis.com/drive/v3/files', { headers: { Authorization: `Bearer ${accessToken}` }, }); if (response.status === 401) { // Token expired — clear it and try once more await GoogleSignin.clearCachedAccessToken(accessToken); ({ accessToken } = await GoogleSignin.getTokens()); response = await fetch('https://www.googleapis.com/drive/v3/files', { headers: { Authorization: `Bearer ${accessToken}` }, }); } return response.json(); } ``` ``` -------------------------------- ### Clear Cached Access Token Source: https://context7.com/react-native-google-signin/google-signin/llms.txt On Android, `clearCachedAccessToken(token)` clears a specific access token from the cache. This is useful when an access token is rejected by a Google API (HTTP 401), allowing you to obtain a fresh token using `getTokens()`. ```typescript import { GoogleSignin } from '@react-native-google-signin/google-signin'; async function callApiWithRefresh() { let { accessToken } = await GoogleSignin.getTokens(); let response = await fetch('https://www.googleapis.com/drive/v3/files', { headers: { Authorization: `Bearer ${accessToken}` }, }); if (response.status === 401) { // Token expired — clear it and try once more await GoogleSignin.clearCachedAccessToken(accessToken); ({ accessToken } = await GoogleSignin.getTokens()); response = await fetch('https://www.googleapis.com/drive/v3/files', { headers: { Authorization: `Bearer ${accessToken}` }, }); } return response.json(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.