After successfully creating a vueJS component, I encountered an error when adding a second "useFetch" call in my <script setup>
tag. The error message displayed was:
A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at `https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables`.
at Module.useNuxtApp (/Users/user/Code/Personal/universityCheckIn/node_modules/nuxt/dist/app/nuxt.js:216:13)
at Module.useAsyncData (/Users/user/Code/Personal/universityCheckIn/node_modules/nuxt/dist/app/composables/asyncData.js:26:38)
at Module.useFetch (/Users/user/Code/Personal/universityCheckIn/node_modules/nuxt/dist/app/composables/fetch.js:63:43)
at checkIfCheckedIn (/Users/user/Code/Personal/universityCheckIn/pages/check-in.vue:51:50)
at init (/Users/user/Code/Personal/universityCheckIn/pages/check-in.vue:75:30)
The relevant part of my <script setup>
section looks like this:
<script setup>
// General Values
const alreadyCheckedIn = ref(false);
const showModal = ref(false);
const lecture = ref(null);
// Modal Values
const lectureName = ref("");
const startTime = ref("");
// Error handling
const displayError = ref(false);
const errorMessage = ref("Please fill in all fields.");
// Fetch lecture data
async function fetchLectureData() {
const lectureDateObj = new Date();
const lectureDateStr = lectureDateObj.toISOString().split("T")[0];
const { data } = await useFetch("/api/lecture", {
method: "GET",
query: {
lectureDate: lectureDateStr,
groupId: 1, //TODO: get the group id from the user
},
});
if (data.value.statusCode === 404) {
return;
}
return data.value.body ? await JSON.parse(data.value.body) : null;
}
async function checkIfCheckedIn() {
const lectureDateObj = new Date();
const lectureDateStr = lectureDateObj.toISOString().split("T")[0];
const { data } = await useFetch("/api/check-in", {
method: "GET",
query: {
lectureDate: lectureDateStr,
userId: 1, //TODO: get the user id from the user
groupId: 1, //TODO: get the group id from the user
},
});
if (data.value.statusCode === 404) {
return false;
}
return true;
}
// Initialize lecture data
async function init() {
const lectureFromDB = await fetchLectureData();
if (lectureFromDB) {
lecture.value = lectureFromDB;
lecture.value.start_time = new Date(
lecture.value.start_time
).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
}
alreadyCheckedIn.value = await checkIfCheckedIn();
}
init();
.
.
.
Prior to adding the checkIfCheckedIn()
function and encountering the error, the fetchLectureData()
function was functioning properly. However, upon further investigation by removing fetchLectureData()
and keeping only one "useFetch" call, the issue dissipated, indicating that the problem arises when having two simultaneous "useFetch" calls.
If using "useFetch" in this manner is not viable, how can I execute two independent API calls upon page load?