0

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 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>

And here's the log and interpolation image: enter image description here

2 Answers 2

1

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[]>([]) // 👍 const prevents accidental overwrites like above

Solution

One solution is to declare events as a ref instead of reactive:

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

onMounted(async () => {
  ⋮
  events.value = response.data // ✅ `events.value` is now the same value as `response.data`
})

demo

Sign up to request clarification or add additional context in comments.

Comments

1

Try to use Object.assign to mutate the reactive data:

 Object.assign(events, response.data)

Or define a state using reactive and define events as field :

let state = reactive({
  events:[]
})
...
state.events = response.data

1 Comment

This doesn't work properly if the new array is smaller than the original (demo).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.