Using Vue 3 and composable files for sharing functions across my entire app has been a great help. One of my composable files, usePluck.js
, is structured like this:
import { api } from 'boot/axios'
export default function usePlucks() {
const pluckUsers = ({val = null, excludeIds = null}) => api.get('/users/pluck', { params: { search: val, exclude_ids: excludeIds }})
return {
pluckUsers
}
}
To utilize this function in my component, I follow these steps:
<script>
import usePlucks from 'composables/usePlucks.js'
export default {
name: 'Test',
setup() {
const { pluckUsers } = usePlucks()
onBeforeMount(() => {
pluckUsers({excludeIds: [props.id]})
})
return {
}
}
}
</script>
Everything was working smoothly until I wanted to call the function without any arguments:
onBeforeMount(() => {
pluckUsers()
})
Unfortunately, this resulted in an error message:
Uncaught TypeError: Cannot read properties of undefined (reading 'val')
. It seems that not passing an object as an argument led to trying to access null.val
.
I'm searching for a solution that allows me to only pass necessary arguments to the function without having to assign null values:
// Avoiding this
pluckUsers({})
// And also this
pluckUsers({val: null, excludeIds: [props.id]})
I simply want to provide essential arguments. Any advice on a different approach would be greatly appreciated.