Tips for successfully sending a dynamic `state` token to useGoogleLogin within react-oauth

Apologies...as a Python developer, I am currently working on incorporating a Google OAuth flow into a react/TypeScript frontend. I have been referencing examples from the react-oauth documentation for guidance. My goal is to dynamically generate a unique state token that will be passed to useGoogleLogin when the user clicks the login button.

const googleLogin = useGoogleLogin({
    ux_mode: "redirect",
    state: "token",  // <= I aim to set this value dynamically upon clicking the login button
    redirect_uri: "http://localhost:3000/auth/google/callback/",
    flow: "auth-code",
    scope: "https://www.googleapis.com/auth/drive.readonly",
    onSuccess: (codeResponse) => console.log('Login successful so far'),
    onError: (error) => console.log('Login Failed:', error)
});

To call this function on the page, it can be done as follows:

<button onClick={() => googleLogin()}>Sign in with Google 🚀</button>

I am struggling to find a solution due to the limitations of using hooks and how to integrate the required logic within useGoogleLogin. However, I believe achieving this should not be too difficult. I have a method available that can request a state token from the backend and can be invoked like this:

const token = await api.user.getStateToken()
. This token is temporarily stored on the backend, and I would like to fetch it synchronously when the login button is clicked.

For comparing purposes, here's how I handle LinkedIn login, which involves manually triggering the OAuth redirect but is straightforward enough to provide insights into what I am trying to achieve.

const onLoginLinkedIn = async () => {
    // Require the backend request for a state token to complete before proceeding. 
    // The state token is utilized to confirm that the subsequent callback from LinkedIn correlates to this specific call
    const token = await api.user.getStateToken()
    await router.push(`https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=${client_id}&redirect_uri=${encodeURIComponent(callback_uri)}&state=${token}&scope=r_basicprofile%20r_emailaddress%20w_member_social`)
}

This function is triggered on the page like so:

<img src="./linkedin/Sign-in-Large---Default.png" alt={"Login LinkedIn"} onClick={onLoginLinkedIn}/>

Is there a way to develop something similar to this setup, but utilizing useGoogleLogin instead of router.push?

Answer â„–1

The function returned by useGoogleLogin can be executed as needed and is automatically updated whenever the state changes. To ensure that your login process updates the state, you should call the googleLogin function which triggers a useEffect for the actual login action:

const [state, setState] = useState<string | undefined>();

const googleLogin = useGoogleLogin({
  ux_mode: "redirect",
  state,
  redirect_uri: "http://localhost:3000/auth/google/callback/",
  flow: "auth-code",
  scope: "https://www.googleapis.com/auth/drive.readonly",
  onSuccess: (codeResponse) => console.log('Login OK so far'),
  onError: (error) => console.log('Login Failed:', error)
});

useEffect(() => {
  if(state) googleLogin(state); // call googleLogin when state is defined
}, [googleLogin, state]);

const onLogin = async() => {
  const token = await api.user.getStateToken()
  setState(token)
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue arises from an absent property in the lib.dom.d.ts file following an update to the most recent TypeScript version

After updating my Angular project to the latest version using the official upgrade guide found here, I encountered an error when running 'ng serve' in the project directory. "ERROR in src/app/menu/menu-tree.component.ts(93,63): error TS2339: Pro ...

The current state of this scenario is not clearly defined within the parent class

Here is the scenario that caught my attention: abstract class Base { public _obj = { name: 'Test' } print1() { console.log(this._obj) } print2() { console.log(this) } } class Child extends Base { print2( ...

Update the Material V4 Style ts file to the latest version, Material V5

I am currently in the process of upgrading from material v4 to v5. The problem I am encountering is related to a styles.ts file that I used to import into my component. Initially, the beginning of the class looked like this: import { defaultFont, prima ...

I encountered a sudden halt in functionality with my NextJs useState feature

'use client' import React, { useState } from 'react'; import Image from 'next/image'; export default function Home() { const [count,setCount] = useState<number>(0) const add = ()=> { setCount(prevCount => ...

Removing spaces within brackets on dynamic properties for objects can be achieved by utilizing various methods such as

I've encountered an issue with my code that involves getting spaces within square brackets for the dynamic properties of an object. Even after searching through Code Style/Typescript/Spaces, I couldn't find any settings to adjust this. Could thes ...

When reaching for the child component in TypeScript, the function document.getElementById may

I am facing an issue with adding "CubeView" from elmarquez/threejs-viewcube to my project. I have created a component and the code for the component is as follows: import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; ...

Error: The 'hot' property is not found in the 'Module' type

Hey there! I recently started using @types/node for aws-cognito-identity provider and unfortunately encountered an error. The error message reads: Class 'Module' incorrectly implements interface 'NodeModule'. Property 'hot' ...

Tips for transferring items between two .ts files

Currently, in my code file numberOne.ts, I am making an API call and receiving a response. Now, I want to pass this response over to another file called numberTwo.ts. I have been attempting to figure out how to transfer the API response from numberOne.ts ...

The ngx-treeview is displaying an inaccurate tree structure. Can you pinpoint where the issue lies?

I have structured my JSON data following the format used in ngx-treeview. Here is the JSON file I am working with: [ { "internalDisabled": false, "internalChecked": false, "internalCollapsed": false, "text": "JOURNEY", "value": 1 } ...

Validation of multiple mat-checkbox selection is necessary in Angular 8

I need help with implementing a validation that ensures "at least one of the dynamic mat-checkboxes is selected" in my HTML code: <div class="form-check" *ngFor="let data of pointsDepart; let i=index" [ngClass]="i == 1 ? 'marginTop': '&a ...

Can you explain the concept of a mapped type and its practical applications?

What is the function of this? And when would be the best scenario to utilize it? ...

Exploring Typescript's ability to recursively deduce object attributes

Imagine having this AnalyticsService class export class AnalyticsService { static sendAnalytics(eventName: string) { console.log(eventName); // logic here... } static EVENTS = { Header: { LogoClicked: "Header: Logo Clicked&quo ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

Leverage React components for efficient code reuse and export modules for

I have Project X, which was built using the command "yarn build" and it generated a main.js file. I am trying to use this main.js file as a dependency for another React project Y. Unfortunately, following the steps from React components and module exports ...

The elusive "AnimationEvent" is nowhere to be found in the realm of Angular 4's '@angular/animations'

Currently on Angular version 4.3.2 Running @angular/cli version 1.2.6 Incorporating TypeScript (v2.4.2) for a specific component that imports import {animate, AnimationEvent, state, style, transition, trigger} from '@angular/animations'; Enc ...

The notion of await goes beyond simply waiting for a promise to be fulfilled

Hey there everyone! I've been struggling with a problem for some time now, and I just can't seem to figure it out by simply searching online. That's why I'm turning to all of you for help. Situation: I'm working on a small applic ...

Is there a way to retrieve the chosen value from an ion-alert radio alert?

async showAlertRadio(heading:string){ const alert = await this.alertCtrl.create({ header: heading, inputs :[ { name : 'Radio 1', type: 'radio', label: 'Radio 1', ...

Issues arise when trying to insert a control based on the index in an Angular Reactive FormArray

Below is the form structure I am working with: this.addForm = this.formBuilder.group({ details: this.formBuilder.array([]), }); To add a new control, I use the following function: nestedFormGroupDetails(control) { control.push( this.f ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

"Exploring the incredible powers of Ionic2, Angular2, HTTP requests, and

Despite all the research I've done on observables, I still struggle to grasp how they function. The HTTP request code snippet is as follows: import { Component, OnInit, Injectable } from '@angular/core'; import { Http, Response, Headers, R ...