DEV Community

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

Posted on

8 1

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

AWS Security LIVE! Stream

Go beyond the firewall

There's more to security than code. Explore solutions, strategies, and the full story on AWS Security LIVE!

Learn More

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay