0

I'm building a vue js web app with the possibility to connect with user's Google account.

The log in process (front-end and back-end) are working fine: the google sign in button is displayed, user clicks on it and it's avatar is showed, without a page reload.

Now, a user is already logged in and refresh the page. The "visual" problem here is that the request to the back-end is done at the end because I cannot instantiate gapi.auth2 before the vue js component/page is loaded.

I've tried this solution from this post, but I cannot call gapi.auth2 in 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()

The error is TypeError: gapi.auth2 is undefined

Is it possible to have the information directly, before the whole page is loaded?

louloulfx
  • 41
  • 8
Kaymaz
  • 454
  • 8
  • 23

1 Answers1

0

I assume that gapi.auth2.getAuthInstance().currentUser.get() is an async task for that you can use the async created hook which is triggered on the creation of your instance and there 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,
  }
})

and make sure you have imported gapi at the top of your script.

Abdelillah Aissani
  • 3,058
  • 2
  • 10
  • 25