Home > other >  Vue 3 Object returns undefined after reload
Vue 3 Object returns undefined after reload

Time:11-03

How to extract other attributes from Keycloak object ? Right now,

If i use,

console.log(keycloak)

it will output whole keycloak object. Even if i reload it stays there on console.

But when i use,

console.log(keycloak.token)

It will output token from keycloak object but when i reload the page it gives me undefined on console.

My Vue Component:

<template>
  <div class="home">
    {{ arrowFunction() }}
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useKeycloak } from "@baloise/vue-keycloak";

export default defineComponent({
  name: "Home",

  setup() {
    const { keycloak } = useKeycloak();
    function arrowFunction() {
      console.log(keycloak);
      return keycloak;
    }
    return {
      arrowFunction,
    };
  },
});
</script>

My Main.ts:

import { vueKeycloak } from "@baloise/vue-keycloak";
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

const app = createApp(App);

app.use(vueKeycloak, {
  initOptions: {
    onLoad: "login-required", // default
  },
  config: {
    url: "https://xxxxxxxxxxxxxx.com/auth/",
    realm: "xxxxx",
    clientId: "xxxxclient",
  },
});
createApp(App).use(store).use(router).mount("#app");

Infos are stored here: enter image description here

CodePudding user response:

The README of the keycloak package shows that the useKeycloak() exposes a few states. One of them seems to be what you wanted to get in the first place (token).

So I'd suggest that instead of only fetching the keycloak Property and trying to get token of that, you might want to get the state you're looking for directly and therefore, I would rewrite your code to

  setup() {
    const { keycloak, token } = useKeycloak();
    function arrowFunction() {
      console.log(keycloak);
      console.log(token);
      return keycloak;
    }
    return {
      arrowFunction,
    };
  },

I never worked with the library, so tell me when I'm missing a major thing, but I think this should work as you want.


Further elaboration:

If we take a look at the documentation of useKeycloak(); we can see that it will return an Object with various Properties. Among those we have keycloak and token.

We are getting the properties of that Object directly by destructuring them on the call.

const { keycloak } = useKeycloak();

will be the same as

const ReturnValue = useKeycloak();
const keycloak = ReturnValue.keycloak;

So we can bind the desired exposed property of the return value by adding it in the curly brackets resulting in:

const { keycloak, token } = useKeycloak();
// Same as:
// const ReturnValue = useKeycloak();
// const keycloak = ReturnValue.keycloak;
// const token = ReturnValue.token;

So what happened initially was, that you were effectively logging console.log(useKeycloak().keycloak.token);

  • Related