Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently,

If I try,

console.log(keycloak)

it will display the entire keycloak object. Even after reloading, it remains in the console.

However, when I do,

console.log(keycloak.token)

It only shows the token from the keycloak object but upon page reload, it returns undefined in the console.

This is 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>

This is 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");

The stored information can be found here: https://i.stack.imgur.com/x7IVE.jpg

Answer №1

Upon reviewing the documentation for the keycloak package on GitHub, it appears that the useKeycloak() function exposes several states, including the token that you were initially trying to access.

Instead of solely retrieving the keycloak property and attempting to access its token, it may be more effective to directly retrieve the specific state you require. With that in mind, I would suggest modifying your code as follows:

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

Although I have not personally utilized this library before, based on my understanding, this adjustment should yield the desired outcome.


Additional Explanation:

By examining the documentation for useKeycloak();, it becomes evident that the function returns an Object containing various Properties, such as keycloak and token.

Through destructuring, we can directly access these properties from the returned Object. For example,

const { keycloak } = useKeycloak();
effectively assigns the value of ReturnValue.keycloak to the variable keycloak.

In essence, by specifying the desired exposed property within the curly brackets during destructuring, we can easily access them like so:

const { keycloak, token } = useKeycloak();
// Equivalent to:
// const ReturnValue = useKeycloak();
// const keycloak = ReturnValue.keycloak;
// const token = ReturnValue.token;

Prior to the suggested modification, you were essentially logging

console.log(useKeycloak().keycloak.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

What is the best library to utilize for uploading an Excel file in a React application?

As a beginner in JS and React, I have a simple question that I hope someone can help me with! I am trying to figure out how to upload an excel file using a form and then extract the data from the rows and columns. For example, I would like to calculate th ...

Tips for Using Threejs Loaders in a React App

Greetings and thank you for taking the time to read my question. ...

Is there a way to seamlessly transition between different Angular components without having to refresh the entire webpage?

I'm currently working on implementing a navigation bar that allows users to switch between three components without having the navbar reload. The goal is for only the new component to load when the user clicks on a different section of the navbar, kee ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

PHP Dropdown List - Default option should be set to "all" (or "Alle")

My website displays data to users based on the State they reside in, with a filter provided through a drop-down list allowing them to select any specific State or view data from all States. Currently, the default selection shows the user data from their ow ...

Preventing an Angular component from continuing to execute after clicking away from it

At the moment, I have a sidebar with clickable individual components that trigger API calls to fetch data. However, I've noticed that even when I click off a component to another one, the old component continues to refresh the API data unnecessarily. ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

shifting the length of o to the right by zero with the

While exploring the polyfill function for Array.includes, I stumbled upon the following lines of code: // 2. Let len be ? ToLength(? Get(O, "length")). var len = o.length >>> 0; // 4. Let n be ? ToInteger(fromIndex). // (If fromIndex is undef ...

Experiencing difficulties integrating relational data with Angular and MongoDB

I have a view where I display 'Transporters'. Each Transporter has multiple 'Deliveries', so I want to associate Deliveries with the corresponding Transporters. My tech stack includes express, mongoose, and angular.js. Here are my mode ...

Cypress error: Unable to access 'uid' property as it is undefined

Recently in my Cypress project with TypeScript support utilizing the Cucumber Preprocessor, an unexpected exception has started appearing: TypeError: Cannot read properties of undefined (reading 'uid') There are instances where changing to a di ...

Other options for positioning background in SVG or using CSS within SVG could include center center alignment settings

I am currently developing a website where I have a div covered by an SVG. When I use this SVG as a background image and apply background-position: center center, it functions as expected. However, my issue arises when I try to add additional CSS in this ma ...

Opting for CSS3 transitions over jQuery animate

Currently, I am working on animating a block of HTML that involves fading in (opacity) and slightly moving from the left (margin-left)... $('.latest-stats').delay(1000).animate({ opacity: 1, marginLeft: '55px' }, 1000, function () { ...

The Quasar Icon Genie CLI transforms square icons into rectangle shapes

Is there a way to prevent cropping when generating icons for my Capacitor app using Icon Genie CLI? I have a 512x512 icon that I am passing to the tool, but the resulting icons are cropped to a rectangle and have a white background on iOS. Here is an examp ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

Concealing forms within an Angular 5 application

I'm currently working on displaying the terms of use on the initial screen along with two buttons. If the user clicks the accept button, they will be directed to the authentication form. However, if they click refuse, the "Refused Terms" screen will a ...

Error message: NestJS encountered a problem with Neovim due to an import prefix missing and the inability to load a local module

This issue can be frustrating as it doesn't affect the functionality of the program. However, upon opening a new or existing NestJS application, all imports are highlighted as errors. For instance, in the main.ts file, there are two imports: import { ...

I want to modify a class in Angular 8 by selecting an element using its ID and adjust the styling of a div

Is it possible to dynamically add and remove classes using getElementById in Angular 8? I need to switch from 'col-md-12' to 'col-md-6' when a user clicks on the details icon. I also want to modify the style of another div by setting d ...

Looking for a solution to the TypeScript & Mantine issue of DateValue not being assignable?

The required project dependencies for this task are outlined below: "dependencies": { "@mantine/core": "^7.6.2", "@mantine/dates": "^7.6.2", "@mantine/form": "^7.6.2", &q ...