skip to Main Content

I keep finding documentation that says variables defined in the <script setup> can be used in the template, but I can’t seem to get this (seemingly simple) piece of code to work.

Pulling the ‘username’ (which is the UUID) from AWS Cognito for the currentAuthenticatedUser, then sending that to DynamoDB through a graphql query to pull the user’s data record. When I console.log that information in the function it works perfectly, but I can’t seem to figure out how to get it to use that variable in the template.

<script setup>
  import { Authenticator } from "@aws-amplify/ui-vue";
  import "@aws-amplify/ui-vue/styles.css";
  import { generateClient } from 'aws-amplify/api';
  import { getStudent } from '../graphql/queries';
  import { getCurrentUser } from "aws-amplify/auth";
  import { Amplify } from 'aws-amplify';
  import config from '../amplifyconfiguration.json';
  import { onMounted } from 'vue';
  Amplify.configure(config);const client = generateClient();
  const firstname = '';

  async function currentAuthenticatedUser() {
    try {
      const { username, userId, signInDetails } = await getCurrentUser();
      return username;
    } catch (err) {
      console.log(err);
    }
  }

  async function loggedInUserData() {
    const loggedInUserId = await currentAuthenticatedUser(); 
    const response = await client.graphql({
      query: getStudent,
      variables: { id: loggedInUserId }
    });
    console.log(response.data.getStudent.firstname);
    firstname = response.data.getStudent.firstname;
  }

  onMounted(() => {
    loggedInUserData();
  });
</script>

<template>
  <div>
  ...
  ...
        <authenticator>
           <template v-slot="{ user, signOut }">
              <div class="pl-36">Hello {{ firstname }}!</div>
              <button @click="signOut" class="ml-36">Sign Out</button>
           </template>
        </authenticator>
     </div>
   </div>
 </div>

2

Answers


  1. I think the document you want is this: https://vuejs.org/guide/scaling-up/sfc.html.

    You should use the Ref function to declare a state. Head to the link to get more details: https://vuejs.org/guide/essentials/reactivity-fundamentals.html.

    Login or Signup to reply.
  2. The variable technically is being used in the template, but only using it’s initial empty string value because the variable is not reactive.

    Make sure to define firstname as reactive in your code:

    import { ref } from 'vue'
    const firstname = ref('')
    

    You used const without ref so actually it was never reassignable to begin with. We can use const with ref/reactive variables because they’re now technically Proxy objects and it’s their inner value that we assign to, hence why we assign new values to refs with the .value property:

    firstname.value = response.data.getStudent.firstname;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search