[Vuejs]-How to get item by Id using Vue 3 Composition API using Axios

0πŸ‘

βœ…

To convert that code to Composition API:

  1. created() hook is effectively the same timing as setup(), so put that code in setup().
  2. this.$route can be accessed via useRoute() (from vue-router@4).
  3. artist can be declared as a data ref, returning it from setup() if used in the template.
  4. To reactively fetch data from the API based on the id parameter, use watch on route.params.id. This watch call returns a function that stops the watcher, which is useful if you need to conditionally unwatch the reference.
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'

export default {
  // 1
  setup() {
     const route = useRoute() // 2
     const artist = ref(null) // 3

     // 4
     const unwatch = watch(() => route.params.id, (newId, oldId) => {
       const result = await axios.get(`https://localhost:5001/api/artists/${newId}`)
       artist.value = result.data

       // run only once
       unwatch()
     })

     return {
       artist
     }
  }
}

Leave a comment