Home > Back-end >  Show loader on Vue 3 async axios request
Show loader on Vue 3 async axios request

Time:12-11

this is my first Vue 3 project...

I'm trying to show a loader during Axios async request. This is my component

<script setup>
  import { defineProps, onMounted, ref, computed } from 'vue';
  import axios from 'axios'
  const props = defineProps({
    publicKey: String
  })

  const tokens = ref([]);

  const loader = computed(() => {
    return tokens.value.length > 0
  })

  onMounted(async () => {
      console.log(loader);
      const url = `https://example.com/${props.publicKey}/nfts/metadata`
      const res = await axios.get(url);
      tokens.value = res.data;
      console.log(loader);
    });

</script>

<template>
  <div v-if="loader">
    <div class='anim-circle'></div>
  </div>

  <div v-else>
  {{tokens}}
  </div>
</template>

It's doesn't work, I try in several ways without success...

CodePudding user response:

I think it should be reactive rather than ref for object(array)

https://v3.vuejs.org/api/basic-reactivity.html

so this is the new code:

<script setup>
  import { defineProps, onMounted, ref, computed } from 'vue';
  import axios from 'axios'
  const props = defineProps({
    publicKey: String
  })

  const tokens = reactive([]);

  const loader = computed(() => {
    return tokens?.length > 0
  })

  onMounted(async () => {
      console.log(loader);
      const url = `https://example.com/${props.publicKey}/nfts/metadata`
      const res = await axios.get(url);
      tokens = res.data;
      console.log(loader);
    });

</script>

<template>
  <div v-if="loader">
    <div class='anim-circle'></div>
  </div>

  <div v-else>
  {{tokens}}
  </div>
</template>

CodePudding user response:

I think the "loader" should be

const loader = computed(() => {return !(tokens?.length > 0)})

Because you want to show the loader, if there are no items in the tokens array. Additionally tokens is a const so you can't reassign it. You should use tokens.push(...res.data) instead.

Furthermore as @ImagiNiha showed, you should use reactive instead of ref.

  • Related