Can you pinpoint the issue with this asynchronous function in Vue3?

Dealing with a simple concept error, I find myself unable to solve it. Within the onMounted hook, everything looks correct - an Array of three objects is displayed. However, when I return it to the template and try to interpolate it, all I see is an empty Array.
Here's the code snippet:

<template>
  <div class="container">
  <h1>Events for good</h1>
    <img alt="Vue logo" src="../assets/logo.png" />
    <EventCard v-for="event in events" :key="event.id" :event="event"/>
    {{ events }}
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive } from 'vue';

import { Event } from '@/types/event';

import EventCard from '@/components/EventCard.vue';

import axios from 'axios';

export default defineComponent({
  name: 'EventList',
  components: {
    EventCard
  },
  setup() {

  let events = reactive<Event[]>([])

  onMounted( async() => {
    const response = await axios.get('http://localhost:3000/events'); 
    console.log(response.data)
    events = response.data
    console.log(events)
  })
    return {
      events
    }
  }
  });
</script>

Take a look at the log and interpolation image here: https://i.sstatic.net/wCJcm.png

Answer №1

events is updated with response.data, which effectively replaces the original reactive() instance in the component's context:

let events = reactive<Event[]>([])

onMounted(async () => {
  ⋮
  events = response.data // ❌ `events` now holds the value of `response.data`,
                         // and the initial value is lost!
})

Note: Using const here can help prevent such errors:

const events = reactive<Event[]>([]) // 👍 const ensures no accidental overwrites like above

Solution

An alternative solution is to define events as a ref instead of reactive:

const events = ref<Event[]>([])

onMounted(async () => {
  ⋮
  events.value = response.data // ✅ `events.value` will take on the value of `response.data`
})

demo

Answer №2

Consider incorporating the Object.assign method into your code to modify the reactive data:

 Object.assign(data, result)

Alternatively, you can create a state using reactive and define the data as a field:

let store = reactive({
  data: []
})
...
store.data = result

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

Retrieve JSON data within an HTML element, where the element is sourced from an AJAX GET response

What is the best way to extract JSON data from the response below? $.get('http://localhost:8000/json', function(response) { alert(response); }); The response is as follows: <div id="dom-target" style="display: none;"> {"logo":"log ...

Encountering issue - SCRIPT5022: Error parsing message from server in Sys.WebForms.PageRequestManagerParserErrorException

I'm in need of assistance. I've developed a web application in .Net 3.5 that utilizes asp.net Master page, update panel, and server controls. The asp.net page created with the Master page includes an update panel that contains other server contro ...

What could be causing my Angular to malfunction?

I've encountered some challenges while trying to run angular on my computer. I have been studying angular through demos on w3 schools that showcase various components. Currently, I am experimenting with this one: http://www.w3schools.com/angular/try ...

Having trouble importing the "@angular/material" module

I'm completely new to working with the MEAN stack and currently running into issues with Angular's material module. I am attempting to bring in the "@angular/material" module into my code, but encountering an error each time I try to import it. T ...

Transferring the AJAX response into a JavaScript variable

New to AJAX and JS here. I am implementing an AJAX code that fetches data from a php service. I am trying to figure out how to store the returned data in a JavaScript variable, which I can then display on the UI. Below is my AJAX code snippet: <script ...

Utilize CountUp.js to generate a dynamic timer for tracking days and hours

I am looking to create a unique counter similar to the one featured on this website https://inorganik.github.io/countUp.js/ that counts up to a specific number representing hours. My goal is to display it in a format such as 3d13h, indicating days and hour ...

Having trouble rendering JSON data on a FlatList component in React Native

After expanding FlatList in console.log and verifying the JSON value, I am facing an issue where the values are not displaying on the list. The data is being passed to the second screen and displayed there, but the first screen remains blank. Any assistanc ...

javascript close the current browser tab

Can someone please help me with a JavaScript code to close the current window? I have tried the following code but it does not seem to work: <input type="button" class="btn btn-success" style="font-weight: b ...

`Is there a way to modify the zAxis of a Paper component in Material-UI?`

Hello, I am curious about how to change the z-axis of a paper from MUI. https://i.sstatic.net/iKXLG.jpg The issue I'm facing is that the carousel is overlapping my menu and I need the menu to be on top of everything. Here is how I have it structure ...

Save a text as a CSV file while also preserving any commas within the

I am trying to export a string to csv format while ensuring that commas inside the string are not treated as separators. For example: [{"name":"ALIASED_LINE_WIDTH_RANGE","value":{"0":1,"1":1}}] Even when ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Using Vue.js, perform calculations on various fields within an array of objects generated by the v-for directive

I am currently learning Vue.js and I have implemented a v-for loop to iterate through an array of objects. However, I now need to calculate a specific field (precoPorKg) within this loop. In order to perform this calculation, the input item.quantidade mus ...

What methods are most effective for showcasing Flash messages within Express.js?

I have a Node.js app in the EJS framework and I am new to JavaScript. Could someone please advise me on the correct way to set flash messages in Node.js? Below is my code which is throwing an error: C:\Users\sad\Desktop\Node Applica ...

Is there a way to extract the "validade" value from the array and retrieve it exclusively?

The following array contains data: {"status":true,"data":[{"id":1,"pessoa_id":75505,"created_at":"2022-02- 01T17:42:46.000000Z","holder":"LEONARDO LIMA","validade&quo ...

What could be the reason behind the unexpected behavior of my Bootstrap 3 carousel?

I'm attempting to replicate this visual effect in my own carousel, featuring semi-transparent images on the left and right sides. However, I'm encountering a negative result with my project when transitioning between slides at : here. This is th ...

Error: The listen function in React + Redux Simple Router is undefined and cannot be found

I've been attempting to configure react + react-router + redux + redux-simple-router without success. I encounter an issue when adding redux-simple-router, resulting in the error message: "[TypeError: Cannot read property 'listen' of undefi ...

"Vue.js Mustache Syntax: Beautifying Data Binding with Curly Br

Each element object in my list array has been numbered using the row index as shown below: {{tableData[props.index-1] = props.index }} The code above worked perfectly fine. Initially, I assumed that it would be the left side value (tableData[props.index ...

What is the best way to create a transparent section within a div to reveal the content below?

My goal is to create a user interface that resembles the design shown in this image https://i.stack.imgur.com/GfiZ8.png One issue I'm facing is how to make the center of the top div circular and transparent, just like in the reference image. I consi ...

Is it possible to implement UseState in Server-Side-Rendering scenarios?

Is it possible to utilize useState (and other react hooks?) with Server Side Rendering? I keep encountering the following error when attempting to execute the code: TypeError: Cannot read property 'useState' of null. Oddly enough, if I disable ...

What is the best way to specify option values for selection in AngularJS?

...while still maintaining the model bindings? I currently have a select menu set up like this: <select class="form-control" ng-model="activeTask" ng-options="task.title for task in tasks"> </select> When an option is selected, it displays s ...