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"
there's alot of parts this url is composed of:
- Base URL:
https://somedomain.com
- Path:
/api/v1/entity/:id/subentity?search=query&sort=property&limit=100&page=1&someFilters=filter1,filter2,filter3#someHash
- Path Variables:
/:id/'
- Query Parameters:
search
sort
limit
page
filters
- 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
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
}
}
Top comments (0)