Passing only certain arguments to a function while omitting others without explicitly declaring null values

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.

Answer №1

import { api } from 'boot/axios'

export default function usePlucks() {
  const fetchUserDetails = ({query = null, ignoreIds = null} = {}) => api.get('/users/details', { params: { search: query, ignore_ids: ignoreIds }})

  return {
    fetchUserDetails
  }
}

I am confident that this solution meets your requirements. The { ... } = {}

UPDATE: This workaround was necessary as the code failed without it, due to the absence of an argument causing issues with object matching in destructuring. Hence, a default value on the parameter object is essential, also referred to as a simulated named parameter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with Safari: File downloaded with name "Unknown" due to Javascript issue

After successfully converting my data to text/csv, I can easily download the file in Chrome. However, when attempting to do so in Safari on an iPad or Mac, it opens a tab with the name "unknown" or "Untitled". The code snippet I am using for this is as fol ...

The file module.js is encountering an error at line 327 because it is unable to locate the module named 'express

Hey there, I'm new to nodejs and whenever I run a file in the command prompt like:- C:\demoData>node demo.js I encounter an error like this: module.js:327 throw err; ^ Error: Cannot find module 'express' at Function.M ...

Could there be an issue with my function parameters, or is there another underlying problem?

Hey there! I've been working on this function, but it doesn't seem to be running quite right. Here's the code: function chooseCols(colTag, tagName) { // Set column name var column = $('.tagChooser:eq(&apo ...

Angular JS Route Hijacking

Currently, I am developing an AngularJS application with Firebase as the backend system. One of my main goals is to require users to log in before accessing any part of the application. To achieve this, I plan on using Firebase's User Authentication ...

Having trouble accessing session value within an express router?

Within my app.js file: app.use(session({ secret: 'secureme123', key: 'hack123', cookie:{ maxAge:1000 * 60 * 60 * 24 * 30 }, store:new MongoStore({ db: 'hack123', host:'localhost', port: 27520, ...

A guide to serving multiple HTML files with Node.js

After creating a mongoDB form using nodeJS, I successfully served the signUp page. However, clicking on any other links to navigate to different pages resulted in an error message saying "Cannot GET /index.html". I am struggling with how to properly serv ...

Tips for emphasizing the letters of the alphabet used in search functionality with Angular

Is there a way to highlight specific alphabets in the searched list instead of highlighting the entire word? Currently, when filtering the memberOffice and memberFacilities lists based on the alphabet entered in the search field, the entire text is highlig ...

Displaying the votes through an advanced system called Ajax voting system

I've encountered a challenge while using an ajax voting system in my project. The issue is that I'm utilizing a div with an id to showcase the votes, but whenever someone clicks on vote up or down in any of the posts (which are generated through ...

Error in Form Validation: inconsistent positioning of relative jump and sticky header

I have a webpage with a web form and a sticky header. When a user attempts to submit the form without filling in required fields using a modern-ish browser, an error message pops up as expected. The issue arises when the sticky header hides the input field ...

Save the ID from the listview in the browser's localStorage

I have a listview that is generated by a loop: for(var i = 0; i < data.length; i++) { var garage = data[i]; $("#content-p").append( "<ul data-role=\"listview\">" + "<li><a href=\"#\" i ...

directive in Angular ordering

After exploring this link, my understanding deepened: http://plnkr.co/edit/k5fHMU?p=preview Upon analyzing the code snippet provided in the link above, I noticed that the Angular app consists of both a controller and a directive. However, there seems to ...

Angular's sanitization script incorrectly modifies the URL value provided in the script src attribute

How can I safely sanitize an external URL to dynamically load a script and remove scripts for a specific component only? Here is the approach I have used: private sanitizeUrl(): SafeResourceUrl { // Value declared in the environment file return ...

How is it that when a function is called with just one parameter, it ends up receiving the entire element?

In my table, I have various item numbers listed with corresponding quantity input fields identified by id="itemNumber". Each line also includes a button that triggers a function (onclick="addItemAndQuantity(itemNumber)") to retrieve inf ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

One opportunity to interact with the menu by clicking only once

I am encountering an issue with a menu div that starts off with opacity set to 0 and visibility hidden. The purpose is for this div to become visible when clicking on another div (a menu that sticks to the top of my page, toggle-able via click). Everythin ...

Customize Vuetify Snackbar timeout function

Can anyone help me with defining a method that will execute after a timeout? Specifically, I would like to trigger a $emit event after a specified timeout, but I am unsure of how to achieve this... <v-snackbar v-model="snackbar" :color="primary" ...

Display detailed information in InfoWindows when markers on a Vue Google Map are clicked

I'm working on creating a map similar to Airbnb's design. Each location marker displays the rental price, and when clicked, a popup with more details appears. However, I'm facing an issue where clicking any marker only shows the details of ...

Uncover the hidden href link that has been obscured using the code javascript:void(0)

Currently, I am in the process of developing a straightforward PHP script to extract the actual link from a website that conceals the real link/key using the javascript:void(0) approach. Upon inspecting the source code, I noticed that the href link is empt ...

Why does Grunt encounter an issue with cdnify, displaying a warning that says: "Caution: Parameters for path.join should be in string format"?

When running grunt in my Yeoman-generated Angular project, I encounter the following warning: Running "cdnify:dist" (cdnify) task Going through dist/404.html, dist/index.html to update script refs Warning: Arguments to path.join must be strings Use --forc ...

Animating Object3D to move closer to the camera in a Three.js environment - currently functional, just requires adjustment of screen position

I have some code that animates an object towards the camera and resizes it to fit half of the screen var vFOV = camera.fov * Math.PI / 180; var ratio = 2 * Math.tan( vFOV / 2 ); var screen = ratio * (window.innerWidth * 0.6 / window.innerHeig ...