Home > OS >  Dynamic axios request url in Vue 3 Composables
Dynamic axios request url in Vue 3 Composables

Time:09-14

I've tried this and it worked:

    const posts = ref{[]}
    const urlEndPoint = 'posts'

    const getPosts = async () => {
           let response = await axios.get('/api/' urlEndPoint)
              posts.value = response.data.data
          }

but that one is not dynamic. My goal is to make the urlEndPoint value reactive and set from the components

then i tried this:

const urlEndPoint = ref([])

but I don't know how to send the value of urlEndPoint constant back from the component to the composables.

I tried these in my component:

const urlEndPoint = 'posts'

and

const sendUrlEndPoint = () => {
        urlEndPoint = 'posts'
    }

but none worked.

is there a way to accomplish this goal? like sending the component name to urlEndPoint value in composable or any other simple way.

CodePudding user response:

Define a composable function named use useFetch :

import {ref} from 'vue'
export default useFetch(){

   const data=ref([])

   const getData = async (urlEndPoint) => {
           let response = await axios.get('/api/' urlEndPoint)
              data.value = response.data.data
          }

  return {
     getData,data
 }

in your component import the function and use it like :

const urlEndPoint=ref('posts')
const {getData:getPosts, data:posts}=useFetch()

getPosts('posts')



  • Related