Home > Blockchain >  Sending some but not all args to a function without defining nulls
Sending some but not all args to a function without defining nulls

Time:08-10

I'm using vue 3 and composable files for sharing some functions through my whole app. My usePluck.js composable file looks like

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
  }
}

In order to make use of this function in my component I do

<script>
import usePlucks from 'composables/usePlucks.js'

export default {
  name: 'Test',

  setup() {
    const { pluckUsers } = usePlucks()

    onBeforeMount(() => {
      pluckUsers({excludeIds: [props.id]})
    })

    return {        
    }
  }
}
</script>

So far so good, but now I'd like to even be able to not send any args to the function

   onBeforeMount(() => {
      pluckUsers()
   })    

But when I do that, I get Uncaught TypeError: Cannot read properties of undefined (reading 'val')

I assume it's because I'm not sending an object as argument to the function, therefore I'm trying to read val from a null value: null.val

What I'm looking for is a way to send, none, only one, or all arguments to the function with no need to set null values:

// I don't want this
pluckUsers({})
// Nor this
pluckUsers({val: null, excludeIds: [props.id]})

I just want to send only needed args. Any advice about any other approach will be appreciated.

CodePudding user response:

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
  }
}

I believe this is what you're looking for. The { ... } = {}

EDIT: It didn't work without this because with no argument the destructuring failed because it can't match an object. That's why you also need a default value on the parameter object, also called simulated named parameter.

  • Related