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

Storing dataset characteristics in a JSON file utilizing Vue.js form response

I am currently working on creating a JSON file to store all the answers obtained from a Form. Some of the input fields have an additional dataset attribute (data-tag). When saving the Form, I aim to extract these 'tags' and include them in the JS ...

Axios Instance class request cancellation

In my Redux-saga project, I am working on implementing a polling function where I need to make a request every second. If there is no response from the endpoint, I want to cancel the previous request and initiate a new one using Axios client. I have organi ...

Having issues with importing momentjs by reference in TypeScript with amd configuration

I'm puzzled by the difference in behavior between these two snippets: import * as moment from "../Typings/moment"; One works, while this one doesn't: /// <reference path="../Typings/moment.d.ts" /> import * as moment from "moment"; It t ...

How can you make a dynamic 360 image that responds to mouse movements using three.js?

Is it possible to achieve a three.js effect similar to the one shown here? We have come across solutions that involve drag&drop for camera angle control, but we are interested in having the mouse position dictate where the camera points. For instance, ...

I am encountering a horizontal scroll bar despite setting the width to 100%

I am just starting out as a beginner in web development. I decided to create a webpage to practice my HTML and CSS skills. However, when I set the width of all elements to 100%, I noticed that I am getting a horizontal scroll bar. I have tried troubleshoot ...

Utilize the Magento extension to seamlessly integrate JavaScript code into the head section of your website

I am attempting to incorporate JavaScript code into all or some pages of my website using an extension. I require a dynamic version (hosted in a .phtml file) of the following script: <default> <reference name="head"> & ...

Enhancing Bootstrap with VueJS for better component ordering

I've been struggling with Vue components in Bootstrap lately. I am attempting to create collapsible Bootstrap content in Vue, and here is the current code: HTML <div class="col-sm main-content" id="main-content"> <p&g ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

The functionality of Jquery and JS lies in working on DOM elements as opposed to

Just to start off, I want to mention that my knowledge of JavaScript and specifically jQuery is quite limited. I've encountered an issue with some JavaScript and jQuery loading on my webpage. 1) I have written some code on JSFiddle http://jsfiddle.n ...

Extract information from a URL without the need for a page reload or user interaction

Recently, I developed a form that accepts YouTube links and extracts the ID using parsing/regex. The function is triggered by clicking a button, which then displays the ID of the URL. Is there a way to show the ID without requiring a button click or page ...

Failure to inherit props in child components when using React-Redux

I've been following a React-Redux tutorial and encountered an error in the first part of the section titled "React Redux tutorial: asynchronous actions in Redux, the naive way". Post.componentDidMount src/js/components/Posts.js:12 9 | ...

Exploring GLTF models with Threejs - just a click away!

I am currently developing a project in three.js where I aim to load a GLTF file consisting of geometric shapes. My goal is to extract information, specifically the name, of the shapes that are clicked within the GLTF file. At this stage, I am using console ...

Pair participants within a game search array

I've been contemplating this issue extensively but I'm struggling to come up with a fast and efficient solution using JavaScript. I have an array of objects representing game searches for random players. The array might resemble the following: co ...

Tips on ensuring Vuex reacts to changes in attributes/properties within objects contained in lists

Within my Vuex store file, there is a variable that starts as an empty list. This list is meant to hold user objects which have properties such as id, firstname, lastname, and more. export const state = () => ({ users: [] }) As the application runs, ...

How can I effectively display a blank menu item for the SelectField component in Material-UI within a React application?

I am using the select-field component from the material-ui framework version 0.15.4 with React version 15.4.0. I am attempting to add a blank menu-item to the select-field in order to allow for deselecting a value in the dropdown field when clicked. Howeve ...

Rendering an Angular page with data using Node.js

I have a scenario for my website where users need to input a URL with a parameter (an ID) and receive back the corresponding page containing information from the database. I am using Angular4 but I am unsure of how to achieve this. It's straightforwa ...

Modify the content in the v-navigation-drawer upon clicking

I am currently working on a project with a v-navigation-drawer and two buttons. The first button is designed to open the drawer, while the second one should change the content of the drawer without closing it. I want the content to update instantly without ...

What could be causing the state object in React to not be updating correctly? There seems to be a discrepancy between the expanded and

Displayed on the console is a screenshot showing <br><br> I am working with React.js, and the object displayed in the image is an element within an array that is part of the state object. I'm puzzled by what's happening. The object a ...

Learn the technique of storing a sequence of functions within a variable using jQuery

For instance, I am looking to assign a sequential process to multiple variables and utilize them in various scenarios. var disable_btn = true; var button_me = $('#contents.getsamplekit .sample-form .form #submit-btn-freeSample-me'); var button_d ...

Is there a way to make Vue.js recomputed properties force a recompute?

Below is the computed property of my component: methods: { addFavoritePlace(place_id) { axios.post('/api/add-favorite-place', { place_id: place_id }) .then(response => { // I require a specific command here. }); }, ...