Undefined variables are returned by declarations in a script setup after an asynchronous call with top-level await

Here is the structure of my Nuxt 3 / Vue 3 component using script setup:

<script setup>
    const content = await useFetch('/api/items/published').then((res) => res.data)
    const items = await content.data.items
    const issues = await content.data.issues
</script>

<template>
    <Gallery :items="items" :layout="layout" @sponsorModalOpen="sponsorModalOpen()" />
</template>

The values of items and issues are coming back as Undefined, possibly because they are not waiting for the initial async call with useFetch to finish before being defined. This behavior seems counterintuitive, as I would expect both the await on useFetch and the variable declarations to block until the prerequisite task is completed.

When I modify the code to directly pass content to the Gallery component like this, it works:

<Gallery :items="content?.items" :layout="layout" @sponsorModalOpen="sponsorModalOpen()" />

It appears that this only functions correctly with optional chaining, indicating that the prop is initially rendered as undefined but updates once the asynchronous fetch operation is done.

Am I misunderstanding the usage of await here? How can I ensure that the variables are not assigned values until the async task is finished, so I can manipulate them (specifically reordering the results)?

Answer №1

After experimenting with different approaches, I finally discovered a workaround for this issue. Instead of sorting the data after fetching it, I implemented the sorting logic directly within the then() callback of the initial fetch request:

const content = await useFetch('/api/items/published').then((res) => {
  const sortedItems = res.data.value.items.sort((a, b) => {
    return b.issueNumber - a.issueNumber
  });
  console.log(res.data.value.issues)
  const sortedIssues = res.data.value.issues.sort((a, b) => {
    const dateA = new Date(a.publishDate)
    const dateB = new Date(b.publishDate)
    console.log(dateA, dateB)
    return dateB - dateA
  });
  return {
    sortedItems: sortedItems,
    sortedIssues: sortedIssues
  }
})

Another potential solution that crossed my mind was utilizing Suspense, although I have not delved into this method yet.

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

Send PHP data through AJAX and retrieve it on a different PHP page

I need to send a variable through an AJAX URL to another PHP page and retrieve it using: $id=$_GET['id']; Here's an example where the value is passed, for instance $id=6. <a id="pageid" href="ifsc-bank.php?id=<?=$id?>"><im ...

Enhance User Experience with jQuery Form Wizard: Automatically Scroll to Focused Input when Moving to Other Input

After utilizing the jQuery Form Wizard, I have successfully created a method to navigate to other input fields within a form. function goTo(id_step, id_input) { $('#demoForm').formwizard('show', id_step); //unfocus first input ...

Having trouble deciphering the request header value within the REST web API

Utilizing Ajax, I am storing the token in the request header and sending it to a Rest API. Here is the request sent to the web API: var xhr = new XMLHttpRequest(); $.ajax({ url: 'http://localhost:32253/api/UserDetail/Authenticate', head ...

Mastering the art of utilizing v-if and v-for with nested objects in Vue.js

Struggling to display nested object content using v-for. I have a prop containing an object, but the div doesn't show when I use v-if="prop". Any help on how to resolve this issue would be greatly appreciated. Below is the syntax I'm currently us ...

Creating a stationary div element solely with Javascript, excluding the use of CSS, jQuery, and HTML

I've been searching all day for a solution to this issue without any success. I apologize if I overlooked any relevant posts on the topic. Currently, I am working with Qualtrics and attempting to implement a textbox with scrolling instructions that fo ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

Angular 4 encounters performance issues when rendering numerous base64 images simultaneously

I'm currently working on a private project that involves using Angular 4 (specifically version 4.1.2). One issue we're facing is related to rendering multiple base64 images on an HTML page. The performance of the application significantly drops w ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Steps for refreshing Google reCAPTCHA on an AJAX-enabled webpage

I am encountering an issue with two captchas on my website. One captcha is loaded upon refresh, while the second captcha is loaded on a different page via ajax. The problem arises when I click on the "No" button after selecting it on the second page. I wan ...

Incorporating search engine optimization into a React project

Currently, I am tackling a React js project and have been assigned the task of incorporating SEO into it. I have attempted to find some open source resources that outline a step-by-step process on integrating SEO, as well as how to implement tags and end ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

When the Button is clicked, the component utilizing the Router fails to appear

My current task involves creating a page where users can choose between two options: Button 1 leads to TestOption.js, while Button 2 redirects to TestOption2 (currently using TestOption for testing purposes). The default landing page is SelectionPage. The ...

Rendering React Js component occurs just once following a state update

My journey with ReactJS is just beginning, and I'm facing an unusual issue which might be due to my unconventional implementation approach. Previously, everything was working smoothly. However, when I tried to introduce new features, things started g ...

How to efficiently filter objects within a child array in an ng-repeat statement, utilizing track by $index to manage duplicates

I have a variable called narrow.searchedMenu that contains 3 arrays of equal length. To display them, I am using ng-repeat with track by $index due to some duplicate elements present. <ul> <li ng-repeat="item in narrow.searchedMenu.desc ...

What steps should I take to resolve the dynamic image src error in Vuejs?

<img :src="userPhoto" alt="User Photo" /> computed: { userPhoto() { var userImage = this.memberdata.userimage return require(`../../../../php/laravel/token/storage/app/uploads/userimages/${userImage}`); } }, ...

The topic at hand pertains to a specific exercise featured in the well-known book Eloquent JavaScript

In this exercise, the final step is to create a recursive function that takes a joined list and an index as parameters. The function's purpose is to find the value in the object within the list at the specified index. The code I have written seems to ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...

What is the best way to include a property with a name in quotes to an object after it has already been declared?

Is there a way to include a property with a quoted name to an object after its declaration? Here's a simplified scenario: var Obj = {} Instead of: Obj.dog = "Woof!"; I want to achieve: Obj."dog" = "Woof!"; Similar to: var Obj = { "dog" : " ...

Refreshing the page causes ngRoute to malfunction or results in an unknown route error

I am encountering an issue with my code. Whenever I refresh the page on localhost:portnumber/home or /todos or /contacts, it crashes -> showing an error "Cannot GET /home" or /todos or /contacts. The same problem occurs if I just enter localhost:port ...

What is the best way to merge 60 related jquery functions into a unified function?

I designed a webpage that serves as an extensive checklist. When you click on the edit button for a checklist item, a modal window opens up. This modal window contains a radio button to indicate whether any issues were found during the check. If "Yes" is s ...