It's quite a simple concept error, but anyway I'm not being able to solve it, I'm making an axios.get() in a onMounted hook, inside the block of the onMounted everything is showing correct ⇾ an Array of three objects. But once I return it to the template and interpolate it to see the value is just an empty Array.
here's the code:
<template>
<div >
<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>
And here's the log and interpolation image:
CodePudding user response:
Try to use Object.assign
to mutate the reactive data:
Object.assign(events, response.data)
CodePudding user response:
events
is overwritten with response.data
, which effectively removes the original reactive()
instance from the component's context:
let events = reactive<Event[]>([])
onMounted(async () => {
⋮
events = response.data // ❌ `events` is now the same as `response.data`,
// and the original value is gone!
})
Note: Using const
here usually prevents these mistakes:
const events = reactive<Event[]>([]) //