Eduardo Robles
Eduardo Robles

Reputation: 515

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:

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();
  }
};

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?

Upvotes: 35

Views: 65032

Answers (5)

FullStack Colombia
FullStack Colombia

Reputation: 71

import { isProxy, toRaw } from 'vue';

let rawData = someData;

if (isProxy(someData)){
    rawData = toRaw(someData)
}

Upvotes: 7

Tarun_vella
Tarun_vella

Reputation: 101

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

Upvotes: 10

mike
mike

Reputation: 363

You can retrieve the Array response object from the returned Proxy by converting it to a JSON string and back into an Array like so:

console.log(JSON.parse(JSON.stringify(this.tickets)));

Upvotes: 8

Katinka Hesselink
Katinka Hesselink

Reputation: 4183

You're not doing anything wrong. You're just finding out some of the intricacies of using vue 3.

Mostly you can work with the proxied array-object just like you would with the original. However the docs do state:

The use of Proxy does introduce a new caveat to be aware of: the proxied object is not equal to the original object in terms of identity comparison (===).

Other operations that rely on strict equality comparisons can also be impacted, such as .includes() or .indexOf().

The advice in docs doesn't quite cover these cases yet. I found I could get .includes() to work when checking against Object.values(array). (thanks to @adamStarrh in the comments).

Upvotes: 5

Joseph Connolly
Joseph Connolly

Reputation: 945

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;

Upvotes: 16

Related Questions