Sending data to functions

Hello all, I'm a beginner with Vue so please bear with me :)

I am facing a challenge where I have a function that retrieves user attributes and based on those attributes, I need to run a GraphQL query in another function. Both functions are under the 'methods' section and are called in the 'created' lifecycle. I tried storing the value in a variable and rendering it in the DOM, but I am unable to pass it to the desired function. I even attempted running the functions in different lifecycle hooks, but that didn't solve the issue.

export default defineComponent({
  name: 'IndexPage',
  data: function() {
    return {
      token: '',
      redirectUrl: '',
      authUser: ''
    }
  },
  methods:{
    async setUser() {
      this.authUser = authUser
    },
    async getAtt() {
        Auth.currentAuthenticatedUser()
        .then(data => (this.authUser = data.attributes['custom:learn_url']))
        .catch(err => console.log(err));
    },
    async getUrl() {
      const id = this.authUser; // This is where i want the id to assign the authUser value
      const learnUrl = await API.graphql({
        variables: { id },
        query: getLearnUrl
      });
      this.redirectUrl = learnUrl.data.getLearnUrl.learnUrl;
    }
  },
  created() {
    this.getAtt();
    this.getUrl();
  }
})

Answer №1

It seems like the issue may be with the implementation of your created() method. The method is calling an asynchronous function getAtt(), so you must ensure that you wait for it to finish before trying to access the authUser variable that was retrieved in the getUrl() function. If not, the variable will remain empty.

To resolve this, modify the created() method to be asynchronous and use the await keyword for the functions.

Example

async created() {
  await this.getAtt();
  await this.getUrl();
}

Answer №2

Following Tamas' recommendation, it is crucial to wait for the outcome of the Auth.currentAuthenticatedUser() function before proceeding.

export default defineComponent({
  name: 'MainPage',
  data: function() {
    return {
      userToken: '',
      redirectLink: '',
      authenticatedUser: ''
    }
  },
  methods:{
    async setUser() {
      this.authenticatedUser = authenticatedUser
    },
    async fetchAttributes() {
        await Auth.currentAuthenticatedUser() // 👀
        .then(data => (this.authenticatedUser = data.attributes['custom:learn_url']))
        .catch(err => console.log(err));
    },
    async fetchLink() {
      const userId = this.authenticatedUser; // Assigning the authenticatedUser value to userId
      const learnLink = await API.graphql({
        variables: { id: userId },
        query: getLearnUrl
      });
      this.redirectLink = learnLink.data.getLearnUrl.learnUrl;
    }
  },
  async created() {
    await this.fetchAttributes();
    this.fetchLink();
  }
})

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 are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Twice the data fetching through ajax on popup is observed using php mysql

I've been struggling for the past two hours. Attempted : location.reload(); reset form Tried many features, but after closing my popup and reopening it or opening another ID, the previous ID data is still visible. This happens continuously for all ...

Guide to using jQuery AJAX to read a JSON file

For the purpose of accessing and reading a json file from my server, I have employed the following code: $.ajax({ type:"GET", url:path, contentType:"application/json; charset=UTF-8", dataType:"json" success:function(response) { ...

When the "/" button is clicked, display a menu and highlight the menu choices for selection

I have been working on developing a similar concept to Notion, and I am facing a challenge with a specific feature. I want a menu to appear when the user clicks "/", providing options to change the current block to their preferred style. Currently, I can c ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

Introduction to React with Typescript: Greeting the World

I am attempting to create a Hello World React application with Typescript. Below is the code I have written. Method 1 works without any issues, but method 2 throws an error. Method 1 - TypeScriptComponent.tsx import React from 'react' import Re ...

Is there a way to deactivate middleware in Node, Express, and Mocha?

My application features a hello world app structured as follows: let clientAuthMiddleware = () => (req, res, next) => { if (!req.client.authorized) { return res.status(401).send('Invalid client certificate authentication.'); } ret ...

Access array information using AngularJS

Sorry for any language issues. I am trying to figure out how to extract an array data from AngularJS in order to save it using Node.js. This is my AngularJS script: angular.module('myAddList', []) .controller('myAddListController&apos ...

Is there a way to display incoming chat messages on the chat box without requiring a page refresh using socket.io?

Having trouble resolving an issue with my application hosted on wpengine, built using WordPress, vue.js, and socket.io for chat functionality. The main concern is that new messages posted in the chatbox do not display until the page is refreshed. I'm ...

How come only the final element is being displayed from an array in JavaScript, rather than all of the elements present

I am facing an issue while attempting to extract specific information from a JSON data and create a new array with key-value pairs. However, instead of getting all the elements, it only returns the last one. Here is my current code snippet: const input = ...

Using a .vue file in an HTML document: A step-by-step guide

After creating a hello.vue file, I am unsure how to actually use it in an HTML file. I have already set up webpack, <template> <p>Hello</p> <p>{{message}}</p> </template> <script> module.exports = { data: ...

Could you display the picture prior to the function commencing?

This is the image that needs to be loaded before the loop begins. <div id="attendenceGridDivLoader" style="display:none"> <img src="<?php echo base_url() . 'images/loader.gif'; ?>" /> </div> <select onchange=checkAll ...

Whenever I adjust the layout of the navigation bar, the edges end up getting clipped

I'm having trouble with the border shape of my navbar. When I try to make it a rounded pill shape, the edges get cut off instead of being properly displayed. https://i.stack.imgur.com/sUN2Y.png Below is the HTML template: <template> <div cl ...

Is there a way to enlarge the font size for a complete tag?

I'm having trouble with a project. One of the tasks is to use jQuery or JavaScript to increase the font size of a paragraph. The console statements are incrementing by +1 with every mouse click (the first click adds 1, the second adds 2, and so on). ...

Issue with thymeleaf causing malfunction in top-bar navigation on foundation framework

Looking for advice on creating a navigable menu using Foundation's "top-bar" component in an HTML template file with Spring MVC + thymeleaf. The menu bar appears but the sub-menus are not displaying when hovering over them. Sub-menus related to main ...

What is the preferred workflow for client-side modules: (Browserify + npm + gulp) or (RequireJS + Bower + gulp)?

As I delve into various client-side Javascript modules workflows for my current Node.JS Express project, I find myself torn between Browserify + npm + gulp and RequireJS + Bower + gulp. While I lean towards CommonJS due to its syntax, the idea of sharing ...

Retrieve the child grid's data source in Kendo using Angular

I am currently working with a master detail grid in Kendo Grid and using the Angular version of the Kendo Grid. One interesting feature I have added is a custom button for adding a new record in each row of the grid. When this button is clicked, a new rec ...

Can anyone provide guidance on implementing pagination with Firebase Realtime Database in Vue.js?

Currently, I am working on implementing pagination for my data from the Firebase Realtime Database. Do I need to switch to Firestore instead? Google's documentation provides detailed information on how to implement pagination using Firestore (https:// ...

Implementing Ideone API functionality on Codeigniter with the use of ajax, javascript, and soapclient

I am new to using Codeigniter and I apologize if my question is basic. I found some code on this site: Working with IDE One API (Full project code available here) and I'm attempting to incorporate it into Codeigniter. I have been able to get it worki ...

PyScript <script type="py-editor"> Issue: SharedArrayBuffer cannot be used in an insecure environment

I am currently using PyScript to execute a basic Python script within my HTML file in order to show a pandas DataFrame. However, upon loading the page in the browser and attempting to run the code block by clicking the run button, I encounter an error rela ...