Initiate gapi.auth2 upon VueJs initialization

I am currently developing a Vue.js web application that allows users to connect with their Google accounts.

The login process, both front-end and back-end, is functioning properly: the Google sign-in button is displayed, the user clicks on it, and their avatar appears without the page needing to be refreshed.

However, I encountered a visual issue when a user who is already logged in refreshes the page. The problem lies in the fact that the request to the back-end is made towards the end because I cannot initialize gapi.auth2 before the Vue.js component/page has finished loading.

I attempted a solution mentioned in this post, but I faced difficulty calling gapi.auth2 within the main app data section:

<script>
  function onLoad() {
    gapi.load('auth2', function() {
      gapi.auth2.init();
    });
  }
</script>
<script type="text/javascript" src="https://apis.google.com/js/platform.js?onload=onLoad"></script>
...
<script type="module" src="main.js"></script>
</body>
</html>

Main.js:

var app = new Vue({
  el: '#app',
  data: {
    user: gapi.auth2.getAuthInstance().currentUser.get()
  }

This results in the error message:

TypeError: gapi.auth2 is undefined

Is there a way to retrieve this information directly before the entire page finishes loading?

Answer №1

If you are dealing with the asynchronous task of

gapi.auth2.getAuthInstance().currentUser.get()
, you can utilize Vue's async created hook. This hook is triggered upon the creation of your instance, allowing you to assign the value to your data:

// import gapi from '....'
var app = new Vue({
  el: '#app',
  async created() {
    try {
      let res = await gapi.auth2.getAuthInstance().currentUser.get();
      this.user = res.data
    } catch (e) {
      console.log(e)
    }
  },
  data: {
    user: null,
  }
})

Ensure that you have imported gapi at the top of your script.

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

Incorporating SSL into an Express web application

I have taken over a project that I want to enhance further. The project is built on Express and Peerjs, with a server and client (vue.js) application in place. One feature of the project involves a video stream. In order to test the application, I need to ...

Issue with PHP functionality not functioning properly

I've been working on implementing an AJAX Form to allow users to upload their profile picture on my website. However, I've encountered some difficulties with the process. I have created a PHP page where the form is supposed to be posted using AJA ...

Adjusting the view of an OpenLayers3 map to encompass various vector layers

My OpenLayers3 map includes an OSM Tile layer and one or more Vector layers. I have a function that allows me to zoom into a single layer successfully: vector.addEventListener("change", function() { map.getView().fitExtent(vectorSource.getExtent(), ma ...

Load External HTML content into webpage along with executing JavaScript code and triggering JS functions upon loading

I'm in search of a super lightweight solution that can effectively load an external HTML file into a page using only vanilla JavaScript. The external file contains HTML, CSS, and JS. Essentially, I want to create a concise JS snippet that loads a butt ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates. I suspect that the canvas, which is ove ...

What steps do I need to take to implement AJAX form authentication?

I have set up a login screen that validates username and password credentials through a php script. When a user enters their information and submits the form, the authenticate.php file executes an LDAP bind. If the credentials are correct, the user is redi ...

Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type fiel ...

How can I pass a specific value, rather than the entire array, in a ReactJS dropdown menu?

I am facing a problem where the entire array is being passed as an argument when I call onchange after getting correct values in the dropdown. Instead of only receiving the selected value, e contains the whole array. Here is the code snippet that demonst ...

Utilizing Django to access a JavaScript variable within server-side template code

I am faced with a challenge on a page that dynamically adds textboxes. In order to access the relevant context variable within these dynamically added text boxes, I need to utilize the 'i' variable in both my javascript and template code. Specifi ...

Guide to integrating Google Maps JS API into a React application without relying on third-party libraries

I'm currently grappling with the concept of integrating external APIs in React and am interested in using Google Maps' API to showcase a map within a child component. My goal is to gain insight into how this can be done without relying on any ext ...

Identifying the device name in Safari on iOS 13 despite the inaccurate display of the user agent - a step-by-step guide

Following the release of Apple's iOS 13, I discovered that window.navigator.userAgent in Safari on iPad iOS 13 is identical to that on MacOS. It appears like this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) ...

Tips for navigating through pagination indexes with Angular 6

Hey there, I'm currently working on a project where I need to automatically click through each pagination index. Initially, only the first index can be clicked. After that, the following page indexes are not clickable. Here's the code snippet: ...

What's the best approach for implementing TimeInput exclusively in React-Admin?

I discovered this helpful code snippet on the React-Admin documentation that allows me to input both a date and time: import { DateTimeInput } from 'react-admin'; <DateTimeInput source="published_at" /> But now I'm wonderin ...

Issue: ENOENT - The requested file or directory cannot be found in the context of an Angular2 and Express.js

I have made some changes to the Angular2 app on GitHub in order to use Express.js instead of KOA. However, when I try to load the app in FireFox, I encounter the following error in the `nodemon` console: Error: ENOENT: no such file or directory The Angul ...

Implementing a post request triggered by a button click in Node.js with Express

How can I invoke a controller from a button click event? I tested it in Postman and it works fine, but I'm having trouble calling it from a button on my front-end. I am using Nodemailer and Node Express to send emails. Here is my code. Can someone p ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Calculate the total amount by multiplying the price and quantity values within nested arrays

I have a collection of objects with nested arrays structured like this [ { orderId: 123, orderStatus: 'Pending', date: 'June 13, 2020', products: [ {product: 'choco', price: 300, qty: 3}, {product: 'm ...

Encountering a loading error with r.js while attempting to optimize

In my main.js file, I have the following configuration for Require.js: /*--- Setting up Require.js as the main module loader ---*/ require.config({ baseUrl: '/javascripts/libs/home/', waitSeconds: 0, paths : { jquer ...