Verify that the API call query parameters do not contain any null values

I need to figure out how to submit only the queryParams parameters with values that are not null. Here's the current code for the submit function:

onSubmit() {        
    const queryParams =
        '&name=' +
        this.name +
        '&date_from=' +
        this.startDate +
        '&date_to=' +
        this.endDate;

    this.callAPI({
        queryParams: queryParams
    });
}

I'm unsure about where to add the check for null values. I know trying something like this is incorrect:

this.callAPI({
    queryParams: queryParams !== null
});

What would be the right way to handle this?

Answer №1

I encountered this issue and decided to create my own custom function to address it.

const customizeParams = obj => {
    const parameters = new URLSearchParams();
    for (let [key, value] of Object.entries(obj)) {
        if (value) { // Validate input here for any specific condition you require
            parameters.append(key, value);
        }
    }
    return parameters;
};

You can use the function by passing an object with parameters like shown below:

{
  name: 'exampleName',
  date: 'someDate',
  ...
}

Answer №2

queryParams is guaranteed to have a value because it is being treated as a string in the concatenation process.

To ensure that name, startDate, and endDate are not empty, each of them needs to be individually checked:

onSubmit() {
    if(!this.name || !this.startDate || !this.endDate){
        return;
    }

    const queryParams =
        '&name=' +
        this.name +
        '&date_from=' +
        this.startDate +
        '&date_to=' +
        this.endDate;

    this.callAPI({
        queryParams
    });
}

Answer №3

The recommended approach is to perform the task as follows:

const queryParams = `${this.name !== null ? '&name=' + this.name : ''}${this.startDate !== null ? '&date_from=' + this.startDate : ''}${this.endDate !== null ? '&date_to=' + this.endDate : ''}`; 

this.callAPI({
        queryParams: queryParams
    });

In this solution, a template string is utilized for efficient variable concatenation within strings. The ternary operator is also employed for concise conditional operations.

Answer №4

It is crucial that queryParams is not null, as you are including '&name=', '&date_from=', and '&date_to' in the string even if this.name, this.startDate, and this.endDate are null or undefined.

To address this issue, consider implementing the following:

onSubmission() {  
     if(this.name && this.startDate && this.endDate)
     {
        const queryParams =
        '&name=' +
        this.name +
        '&date_from=' +
        this.startDate +
        '&date_to=' +
        this.endDate;

        this.makeAPICall({
           queryParams: queryParams
         });

     }     
   }

Answer №5

Easy Method

handleSubmission() {      

    const { username, start, end } = this;

    let queryParams = ``;

    if(username) {
        queryParams.concat(`&username=${username}`)
    }
    if(start) {
        queryParams.concat(`&start_date=${start}`)
    }
    if(end) {
        queryParams.concat(`&end_date=${end}`)
    }

    this.triggerAPI({
        data: queryParams
    });
}

Answer №6

Create an object with various values, remove any empty ones, and then construct a query string dynamically:

const data = {
    brand: this.brand, 
    price_min: this.minPrice, 
    price_max: this.maxPrice
};

const queryString = Object.keys(data)
    .filter(key => data[key] !== null)
    .map(key => `${key}=${encodeURIComponent(data[key])}`)
    .join('&');

this.sendRequest({ queryString });

Example:

const data = {
  apple: 'fruit',
  banana: null,
  cherry: 25
};

const queryString = Object.keys(data)
  .filter(key => data[key] !== null)
  .map(key => `${key}=${encodeURIComponent(data[key])}`)
  .join('&');
  
console.log(queryString);

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

The issue with the AngularJS component layout engine is that the fxLayoutAlign attribute set to "stretch" is not

It seems that when using the angular/flex-layout along with angular/material2, the fxLayoutAlign="stretch" directive is not functioning correctly. However, the directives fxLayoutAlign="start" and fxLayoutAlign="end" are working as expected. You can see th ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Ideas for displaying or hiding columns, organizing rows, and keeping headers fixed in a vast data table using jQuery

My data table is massive, filled with an abundance of information. Firstly, I am looking to implement show/hide columns functionality. However, as the number of columns exceeds 10-12, the performance significantly decreases. To address this issue, I have ...

Spinning Earth around in circles

I am attempting to create a rotation of the Earth around its tilted axis using Three.js. I came across this helpful solution and tried implementing it in my code, but unfortunately, it doesn't seem to be working as expected. After running the code, I ...

There seems to be a problem with the template for the EmployeeCreateComponent

I have recently started learning Angular and am currently working on a project involving httpclient and httpservice for a CRUD application. However, when I try to compile using ng serve in VS Code, I encounter the following error: error: ERROR in src/app ...

Pinia has not been instantiated yet due to an incorrect sequence of JavaScript file execution within Vue.js

I'm currently developing a Vue.js application using Vite, and I have a Pinia store that I want to monitor. Below is the content of my store.js file: import { defineStore } from 'pinia'; const useStore = defineStore('store', { st ...

What is the best way to increase a numerical input?

While experimenting with HTML input elements, I decided to utilize the step attribute. This allowed me to increment the current value by 100 when clicking the up or down arrows in the input field. However, I discovered that the step attribute restricts th ...

Is there a way to retrieve both the name of the players and the information within the players' profiles?

Just dipping my toes into the world of Javascript and jQuery while attempting to create an in-game scoreboard for Rocket League, I've hit a bit of a roadblock. Here's the console log output of data from the game: I'm particularly intereste ...

Choosing only those elements that are not children of parents with a specific class by utilizing the `.not()` method

I am attempting to target all elements having the class .select that are nested somewhere within the DOM tree. The only condition is that these elements should not have any ancestors with the class .forbidden. This means it will not detect any elements ...

Steps to generate a fresh array from a given array of objects in JavaScript

Looking to transform an existing array into a new array of objects in Vue.js. Here's the initial array : import { ref } from 'vue'; const base_array = ref([ {id: 1, name: Pill, timing: [morning, noon, evening, night]}, {id: 2, name: Ta ...

Using Angular's ng-if directive to close an HTML tag

I have a complex table structure with a td element that I need to conditionally close before or after certain events. Using the NG-IF directive is presenting challenges as it interferes with closing the TD tag within the NG-CONTAINER. Is there a way around ...

Making sure javascript functions properly after loading content through Ajax in Wordpress

I'm currently facing an issue with loading content through Ajax. I'm encountering difficulties in getting the Woocommerce javascript to function properly when I am loading a product via Ajax. The content is being loaded in the following manner: ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

Converting Base 64 to plain text using Javascript

When working on the Server in WebApiController, I have the following Byte array: private Byte[] bytes = new Byte[21]; Once it is filled, it looks like this: bytes = new byte{127,253,159,127,253,223,127,253,255,127,252,63,0,1,192,127,252,255,127,253, ...

Access a Map URL through a native mapping application on your device

Q: I'm looking to open a specific type of link on the Native Map app. Can anyone recommend a plugin that would work for this scenario? https://www.google.com/maps?q=15405 Hebbe Ln+Au... I tried using the Capacitor Browser plugin and it worked well o ...

Everlasting Dropdown in AngularJS Always Open Mode

I am currently working on my first AngularJS App and I am facing some issues with creating a Dropdown menu. Here is the HTML code I have: <div class="btn-group" dropdown> <button type="button" class="btn btn-danger">Action</button> & ...

Is there a way to clear the list after each input is made?

Looking for help with the Ping Pong Test. Whenever I click Start and enter a number, it just keeps adding to the list. How can I make it reset the list after each input? $(document).ready(function() { $("#Start").click(function() { ...

Guide to setting up react-styleguidist, developing with Create React App, using Typescript, incorporating Material UI, and including

Struggling to configure react-styleguidist (RSG) with Create React App 3 (CRA), Typescript, Material UI, and styled-components. Currently encountering an error: ./node_modules/react-styleguidist/lib/client/rsg-components/ReactExample/ReactExample.js Modul ...

Issues with implementing Dark mode in TailwindCSS with Nuxt.js

After spending a couple of days on this, I'm still struggling to get the dark mode working with Tailwind CSS in Nuxt.js. It seems like there might be an issue with the CSS setup rather than the TypeScript side, especially since I have a toggle that sw ...

Seamless Navigation with Bootstrap Navbar and SmoothScroll

Currently, I have a custom-built navbar that functions perfectly, with full mobile responsiveness. However, I am facing an issue with the nav-item's (headings). The nav-item's direct users to different sections of the same page using #. I have i ...