Exploring the use of functions in the setup method of Vue 3

I'm currently working on a simple app and utilizing mock-json-server to mimic http requests.

Within my project, I have defined a function designed to retrieve the necessary information:

import { ref } from 'vue'

const getScores = () => {
const scoringPass = ref([])
const error = ref(null)

const load = async () => {
  try {
    let data = await fetch('http://localhost:8000/scores', {
    method: 'get',
    headers: {
        'content-type': 'application/json'
    }})
    if (!data.ok) {
          throw Error('no data available')
    }
    scoringPass.value = await data.json()
    console.log(scoringPass.value)
  } catch (err) {
    error.value = err.message
    console.log(error.value)
  }
}
return { scoringPass, error, load }
}

export default getScores

This function is then called within the setup function of my component :

<script lang="ts">
    import { defineComponent } from 'vue'
    import Pass from '@/components/Pass.vue'
    import getScores from '../composables/getScores.js'

    export default defineComponent({
    setup() {
      const numeroDossier = '25020230955000004'
      const { scoringPass, error, load } = getScores()

      load()
      return { numeroDossier, scoringPass, error }
    },
    components: {
      Pass,
     },
    })
</script>

Although I can see the data in console.log(scoringPass.value) inside the function, the load() function within the setup section does not seem to work and I am unable to determine why. It seems to be called, yet I am unable to retrieve the data.

When I execute console.log(load()), the output is as follows:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

Any assistance would be greatly appreciated. Thanks.

Answer №1

load() is an async function, which means it returns a Promise. In order to access the data it loads, you need to use await. However, as load() does not actually return anything, you will still not see any data. If you want load() to provide the initial value of scoringPass, then it should explicitly return that value:

const load = async () => {
  try {
    ⋮
    return scoringPass.value
  } catch (err) {
    ⋮
    return null
  }
}

To retrieve the result of load(), you can wrap the call in an async function and await the call, or chain a .then() callback:

export default defineComponent({
  setup() {
    ⋮
    const logLoadResults = async () => console.log(await load())
    logLoadResults()

    // or
    load().then(results => console.log(results))
  }
})

Do not declare setup() as async because this would turn your component into an async component, requiring a <Suspense> element in a parent component to render it.

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

Check if a Discord.js bot responds based on whether a user holds a designated role

I'm looking to make my bot respond to a specific role. If the user does not have that role, I want the bot to reply with a message saying "You are not allowed to perform this command." Here is the code snippet I am using: client.on("message", (message ...

Exploring the world of Node.js with fs, path, and the

I am facing an issue with the readdirSync function in my application. I need to access a specific folder located at the root of my app. development --allure ----allure-result --myapproot ----myapp.js The folder I want to read is allure-results, and to d ...

Using javascript to generate fresh dictionaries

Struggling to translate a C# "function" into JavaScript - any advice or tips? Here is the C# snippet: var parameters = new Dictionary<string,string> { { "link", "http://mysite.com" }, { "name", "This is an test" } }; I believe I need to ut ...

AngularJS Splice Function Used to Remove Selected Items from List

I previously inquired about a method to remove items from the Grid and received a solution involving the Filter method. However, I am specifically looking for a way to remove items using the Splice Function instead. You can find my original question here: ...

Perform the same actions on every element within the ul li

I'm facing an issue with my unordered list, where each list item contains a span element with an image inside. My goal is to set the background-image of each span to be the same as the image it contains, while also setting the opacity of the image to ...

Determine how to use both the "if" and "else if" statements in

/html code/ There are 4 textboxes on this page for entering minimum and maximum budget and area values. The condition set is that the maximum value should be greater than the minimum value for both budget and area. This condition is checked when the form i ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Navigating Google Oauth - Optimal User Sign in Locations on Frontend and Backend Platforms

What are the distinctions between utilizing Google OAuth versus implementing user sign-ins at the frontend of an application, as opposed to handling them on the backend? For instance, managing user authentication in React to obtain the ID and auth object ...

Utilizing CSS to Display a Variety of Colors within a Text String

Is it possible to style different words in a sentence with various colors using only CSS, without using the span element? For instance, how can I make the word "Red" appear in red, "Blue" in blue, and "Green" in green within an h1 tag? ...

Guide on setting default attributes for all properties of an object at once

Currently, I'm in the process of developing an AngularJS service provider (function) that achieves the following objectives: Gathers data from multiple tables within an SQLite database Delivers the resulting object to various controller functions S ...

Loading components dynamically with axios is a valuable feature

Can this be achieved? There is a spinner component. axios: action() { SPINNER (component) -- activate axios.get('/store', { params: { something } }) .then ((resp) => { SPINNER (component) -- ...

Can the repeated use of AJAX function calls at regular intervals adversely affect the speed of the application?

On a specific page of my application, I have been using an AJAX function continuously as shown below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { $.ajax({ ...

Build a unique array of identifiers extracted from an object

I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. const initialState = useMemo(()=> { return dataTable.filter(result => favorites.some(favorite => result.id === favorite.id)) },[ ...

When I try to run Parcel, my ReactJS website just won't deploy in a serverless environment

For a while now, I've been working on a website using serverless. Everything was going smoothly until this morning when I encountered an issue with pushing updates from my site to the serverless platform. When trying to push, I received the following ...

Tips on transforming a grouped object into a table organized by column with the help of Lodash

Looking at my array data: [{ id: '1234', year: 2019 , name: 'Test 1- 2019', rate: 1}, { id: '1234', year: 2020, name: 'Test 2 - 2020', rate: 2 }, { id: '1234', year: 2020, name: 'Test 3 - 2020&apos ...

Mastering the art of jQuery scrolling: A step-by-step guide

Is there a way to utilize jQuery for scrolling purposes? For example, transforming this: <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#home">Home <span class="sr-only">(current)</span></a> ...

Leveraging PrimeFaces and the p:ajax component, trigger Ajax within an inputText field only when keystrokes lead to changes in the field

I am currently utilizing PrimeFaces and have a p:inputText field that requires updating certain components on the view based on the most recent keystroke within that p:inputText. Below is the code snippet: <p:inputText value="#{customerLController.surn ...

Using a responsive menu (mmenu) can lead to an increase in Cumulative Layout

I've implemented mmenu as a responsive menu on my website. Recently, I discovered errors in Google's search console related to high CLS (Cumulative Layout Shift). Upon further investigation, I noticed that when loading my page in "slow" mode for ...

Number input in JavaScript being disrupted by stray commas

On my webpage, there are elements that users can control. One of these is a text input field for numbers. When users enter digits like 9000, everything functions correctly. However, if they use comma notation such as 9,000, JavaScript doesn't recogniz ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...