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
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.
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:You used
const
withoutref
so actually it was never reassignable to begin with. We can useconst
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: