-1

I am trying to get data from an API and want to reuse it inside my script. I am using a ref to store the data. Usually i can access my data via myRef.value. But i do observe some behaviour that makes it complicated to access my data inside the proxy.

This is my request inside a composable.

export default function (url) {
  const data = ref([]);
  const count = ref(0);
  const page = ref(1);
  const isLoaded = ref(false);
  const getUrl = computed(() => {
    if (page.value > 1) {
      return `${url}?page=${page.value}`;
    } else return url;
  });

  watchEffect(async () => {
    axios({
      url: getUrl.value
    })
      .then((res) => {
        data.value = res.data.results;
        count.value = res.data.count;
        isLoaded.value = true;
      })
      .catch((err) => console.log(err));
  });

  const updatePage = (newPage) => {
    page.value = newPage;
  };

  return {
    data: data,
    count,
    page,
    updatePage
  };
}

The output of those 2 logs is the following: output of the 2 console.log()

So what is happening here? I assigned red.data.results to data.value. But logging those 2 gives different results. Accessing a ref's .value should return the proxy's content, but here we see a proxy again.

I do find workarounds, but i would like to understand before i avoid this.

haligh
  • 9
  • 3

1 Answers1

0

It looks like your data variable is not a ref, but a Proxy, most likely because you ran it through reactive(). When you access the data again, Vue wraps it into a Proxy to keep reactivity:

const { reactive, toRaw } = Vue;

const data = reactive({})
const arr = [{id: 1}, {id:2}]
data.value = arr
console.log('`data.value === arr`:', data.value === arr)
console.log('`toRaw(data.value) === arr` :', toRaw(data.value) === arr)
console.log('prints the array in the snippet console, check browser console', data.value)
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
  • I pasted the complete function to show, that i am not setting it to a reactive. Maybe vue does internally, but then thats exactly the part i want to understand. – haligh May 02 '23 at 10:51
  • @haligh Please provide a minimal reproducible example of the problem – Moritz Ringler May 02 '23 at 11:02