Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Array converted to Proxy object

I'm new to Vue. While making this component I got stuck here.

I'm making an AJAX request to an API that returns an array using this code:

<script>
import axios from 'axios';
export default {
  data() {
    return {
      tickets: [],
    };
  },
  methods: {
    getTickets() {
      axios.get(url)
        .then((response) => {
            console.log(response.data) //[{}, {}, {}]
            this.tickets = [...response.data]
            console.log(this.tickets) //proxy object
          })
    },
  },
  created() {
    this.getTickets();
  }
};
</script>

The problem is, this.tickets gets set to a Proxy object instead of the Array I'm getting from the API.

What am I doing wrong here?

like image 793
Eduardo Robles Avatar asked Nov 19 '20 18:11

Eduardo Robles


Video Answer


2 Answers

Items in data like your tickets are made into observable objects. This is to allow reactivity (automatically re-rendering the UI and other features). This is expected and the returned object should behave just like the array.

Check out the reactivity docs because you need to interact with arrays in a specific pattern or it will not update on the ui: https://v3.vuejs.org/guide/reactivity-fundamentals.html

If you do not want to have reactivity - maybe you never update tickets on the client and just want to display them - you can use Object.freeze() on response.data;

like image 194
Joseph Connolly Avatar answered Sep 26 '22 19:09

Joseph Connolly


if you want reactive information use toRaw https://vuejs.org/api/reactivity-advanced.html#toraw

    const foo = {}
    const reactiveFoo = reactive(foo)
    
    console.log(toRaw(reactiveFoo) === foo) // true

or use unref if you donot want ref wrapper around your info

https://vuejs.org/api/reactivity-utilities.html#unref

like image 6
Tarun_vella Avatar answered Sep 25 '22 19:09

Tarun_vella