DEV Community

Cover image for A better way to work with URLs using vueUse useFetch() + useUrl()
Ahmed Chakhoum
Ahmed Chakhoum

Posted on

A better way to work with URLs using vueUse useFetch() + useUrl()

Problem when dealing with URLs:

consider the following URL:

"https://somedomain.com/api/v1/entity/:id/subentity?search=query&sort=property&limit=100&page=1&filters=filter1,filter2,filter3#someHash"
Enter fullscreen mode Exit fullscreen mode

there's alot of parts this url is composed of:

  1. Base URL: https://somedomain.com
  2. Path: /api/v1/entity/:id/subentity?search=query&sort=property&limit=100&page=1&someFilters=filter1,filter2,filter3#someHash
  3. Path Variables: /:id/'
  4. Query Parameters: search sort limit page filters
  5. Hash suffix: #someHash

working with REST APIs / Links using only string interpolation or custom code to change query parameters or path variables this can get very cumbersome and quite tedious
specially when using the useFetch() hook from VueUse, since it have no built-in way to deal with (params, path variables..etc) similar to a library like axios have

Solution:

I made a Vue.js Composition API hook vue-useUrl that solve this problem in a convenient way

let's redo the previous example using useUrl()

const { url, queryParams, pathVariables, hash, path, disableCSV } = useUrl({ 
    path: '/api/v1/entity/:id/subentity',
    pathVariables: {
      id: 1001
    },
    queryParams: {
      search: 'query',
      sort: 'propery',
      limit: 100,
      page: 1,
      filters: [ 'filter1', 'filter2', 'filter3' ]
    },
    hash: 'someHash'
}, 
'https://somedomain.com')

console.log(url.value) // return https:/somedomain.com/api/v1/entity/0/subentity?search=query&sort=propery&limit=100&page=1&filters=filter1,filter2,filter3#someHash
Enter fullscreen mode Exit fullscreen mode

you can work with query parameters, path variables, hash, path as a javascript variables, and the cool thing is changing any value from this variables will trigger an URL rebuild, url will always reflect query changes

Integration with useFetch():

import { useFetch } from "@vueuse/core"
import { useUrl } from "vue-useurl"

export function useApi() {
  const { url, queryParams, pathVariables, path } = useUrl({ 
      path: '/users/random_user',
      queryParams: {
        size: 10
      },
      pathVariables: {},
      hash: ''
  }, 
  'https://random-data-api.com/api')

  const { isFetching, error, data } = useFetch<any[]>(
    url,
      { initialData: { results: [] }, refetch: true }
    )
    .get()
    .json()
  return {
    isFetching,
    error,
    data,
    url,
    queryParams,
    pathVariables,
    path
  }
}
Enter fullscreen mode Exit fullscreen mode

NPM Package
Github repo

Top comments (0)