Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make api call within created hook in vue 3?

Came back to vue after long break. In my solution im using composition api where I need to fetch some data once the component is created so I can display it later on. In my current solution, template is kinda rendered before the call has been made. Probably stupid mistake but still I cannot figure it out (in vue 2.0 it was clear – created() hook).

<template>
  <div>
      <div class="row mb-2 border-top border-bottom" v-for="pizza in pizzas" :key="pizza">
        <div class="col-sm-2">
          <img alt="Vue logo" src="../assets/logo.png" style="height: 100px; width: 135px;">
        </div>
        <div class="col-sm-2 mt-4">
          {{pizza.name}}
        </div>
        <div class="col-md offset-md-2 mt-4">
          price
        </div>
        <div class="col-sm-2 mt-4">
          <button class="btn btn-primary" type="submit">Add</button>
        </div>
      </div>
  </div>
</template>

<script setup>
import {api} from "@/api.js"

let pizzas = null

const GetPizzas = async ()=>{
    await api.get('pizza/pizzas/')
    .then(response=>{
        pizzas = response.data
    })
}
GetPizzas()
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The list of available hooks in Composition API is here:

The closest thing to Options API’s created is running the code in setup() function. However, to avoid having to guard the template with v-if="pizzas", you should instantiate it as an empty array.

And, obviously, you want it to be reactive, so it’s ref([]), not just [].

<script setup>

import { ref } from 'vue'
import { api } from '@/api.js'

const pizzas = ref([])

const GetPizzas = async () => {
  await api.get('pizza/pizzas/').then((response) => {
    pizzas.value = response.data
  })
}
GetPizzas()

</script>

Notes:

  • <template> can remain the same, since we initialise pizzas as empty array. If you initiate it as anything falsey, you need a v-if="pizzas" guard on the root wrapper element.
  • refs require assignment to their .value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading