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

Error message: Unable to split path as a function when utilizing React hook forms in conjunction with Material UI

Check out this code snippet: <TextField name="name" required className='my-2 mx-auto' label="Full Name" variant="standard" style={{ "width": "60%" }} value={name} onChange={(event) => { set ...

Identifying circular interdependencies within a project

Recently, I encountered an issue with circular dependencies in my project. While I was able to resolve it, I would like to prevent this from happening again in the future. I am considering creating a plugin that can detect circular dependencies throughout ...

Disabling a button after it's been clicked using Vue.js

I have a button on my website that grants bonuses to the user. This button has multiple conditions within it: <button class="btn btn--small btn--purple" :disabled="isDisabled" @click="takeBonus">Take</button> < ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

How can I enter a single backslash for location input in node.js without using double backslashes?

I have a project where the user needs to input a word to search for in files along with the folder location. However, I am struggling to write code that allows the user to input the location using single backslashes instead of double backslashes. const fol ...

The tabbing feature in bxslider disrupts the alignment of slides, making it

After encountering accessibility issues, I upgraded the bxslider library to version 4.2.3 for better support. Check out this example of bxslider where you can easily tab through the controls: http://jsfiddle.net/qax7w8vt/2/embedded/result/ The problem a ...

Error in Quasar application: essential modules were not installed properly via npm

After creating a quasar app using quasar create and confirming it worked with quasar dev, I decided to upload the code to GitHub for collaboration. I created a repository and uploaded everything except for node_modules and package-lock.json. Next, I delet ...

After deploying a Next.js project on an Ubuntu server, dynamic pages are returning a 404 error

I've been putting in a substantial amount of time on this project. I'm encountering some 404 errors on my dynamic pages, even though they work perfectly fine on localhost. I've tried using revalidate and playing around with fallback: true an ...

What are some effective strategies for implementing Laravel's localization feature in conjunction with Vuejs?

One of the things I really appreciate about Laravel localization is how simple and easy it is to use, but I'm struggling with integrating it with Vue Components. Any guidance would be greatly appreciated. ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

jQuery automatic slider for seamless transitions

I am in need of assistance with the coding for a website I'm currently constructing at www.diveintodesign.co.uk/ChrisMcCrone/index.html The coding being used is sourced from http://jquery.malsup.com/cycle/ The central large image functions as a slid ...

Using TypeScript without specifying a specific argument in the any type

My function accesses local/session storage, but there is a condition that it can only be called if the window is defined. This function takes a generic args argument which I simplified to have a type of any[]. While using the useSessionStorage function, ...

Seamless changes with graceful fades while transitioning between classes

Is it more efficient to handle this in CSS than using jQuery? I'm not entirely sure. If anyone has a solution, that would be greatly appreciated. However, I am currently facing an issue with the jQuery method I have implemented. It successfully fades ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

How can I load data from the server into CKEditor in React.js once the data is loaded?

Need to make changes in my code for editing an article item: const [contentEditor, setContentEditor] = useState(null); useEffect(() => { async function getLoadData(){ setitem(""); setContentEditor("" ...

Developing components with jQuery

I have a JavaScript program that works perfectly when I use the following line of code: li = $("<li data-role='collapsible' data-iconpos='right' data-inset='false'></li>"); However, if I change the above line ...

Any tips on silencing webpack's constant nagging about the "Critical dependency: require function is used in a way..." warning message?

My immediate goal is to resolve this warning. However, it seems that a different approach may be necessary. I have developed an npm library for date/time functions with most of the code being general-purpose and compatible with both Node.js and web browse ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Can we guarantee the uniqueness of a function parameter value during compilation?

I have a set of static identifiers that I want to use to tag function calls. Instead of simply passing the identifiers as arguments, I would like to ensure that each identifier is unique and throws an error if the same identifier is passed more than once: ...

Can WikiData be accessed by providing a random pageId?

My current project involves creating a Wikipedia Search App with a 'Feel Lucky' button. I have been trying to figure out if it's possible to send a request for Wikidata using a specific pageid, similar to the code below: async function lucky ...