Custom Axios route with an optional parameter that may be undefined

I'm trying to figure out how to pass in a value for an optional parameter, but the issue is that 'undefined' is being treated as a string instead of the way I want it to behave. Any ideas on what I might be missing here? The default route should be /api/todo/get/ and I know I could just omit 'showAll', but I'd prefer to avoid using an awkward if else construct. Thanks!

const getTodos = (showAll = undefined): Thunk<Promise<void>> => (dispatch) => {
  dispatch(setTodos([]));
  return axios.get(`/api/todo/get/${showAll}`).then((res) => {
    dispatch(setTodos(res.data));
  });
};


router.get("/get/:includeCompleted?", (req: Request, res: Response) => {
    const includeCompleted = req.params.includeCompleted;
    console.log(req.params.includeCompleted);
    return database
        .raw<Todo[]>(
            `
        SELECT *
        FROM todo
        WHERE :includeCompleted = 1 OR completedDate IS NULL
    `,
            {includeCompleted: includeCompleted ? 1 : 0}
        )
        .then((data) => res.status(StatusCodes.OK).json(data));

});

Answer №1

If you want to check for the falsiness of the variable showAll using short-circuit evaluation, you can simply return an empty string if it evaluates to falsey:

return axios.get(`/api/todo/get/${showAll || ''}`)

Update: One of the comments mentioned that short-circuit evaluation may be too strict if you still want values like 0 or false to be sent to the route. In such cases, you can use the nullish coalescing operator:

return axios.get(`/api/todo/get/${showAll ?? ''}`)

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

Issue with parameter in Angular 2 component

I've encountered an error when attempting to add a service to the constructor of a component. The specific error message I'm receiving is "Can't resolve all parameters for RecordComponent". Any insights into why adding the service to the con ...

CORS is preventing the successful logout functionality of Spring security

Tools Used: The technologies utilized in this project are Spring Security and Spring Boot on the backend, along with ReactJs and axios on the front-end. Desired Outcome: Upon clicking the "logout" button on the front-end, my goal is to successfully log ou ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Creating an axios URL using Vue data results in receiving the value of undefined

I'm currently experimenting with axios to retrieve data from openweathermap. I've been working on constructing the URL by utilizing various methods to extract latitude and longitude from the user's browser, followed by a function call to pie ...

Maximizing the potential of GSON in ensuring accurate data retrieval for the 5-day forecast on the

As I work on creating a weather app, I am utilizing the 5-day forecast data from the openweathermap API. I am seeking feedback on whether my code is properly parsing and connecting to the API, especially since it involves retrieving more data than just the ...

Exporting the interface for the state of the redux store

After setting up a redux module, I have organized the following files: //state.tsx export default interface State { readonly user: any; readonly isLoggedIn: boolean; } //types.tsx export default { REQUEST: 'authentication/REQUEST', SUC ...

Dealing with text overflow within a column and ensuring that the text always expands horizontally to align with the column width

I have implemented a file input feature that displays the selected file's name in a column. However, when the file name is too long, it expands vertically which causes readability issues. There is an option to force the text to expand horizontally, b ...

What is the best way to retrieve a date range specific to a month?

My goal is to extract the dateRange within a month starting from the beginning of the week to the end of the week. For instance, if I select January 2020 as the month, the dateRange should cover data from December 30, 2019 to January 31, 2020. For Februar ...

What is the most effective way to organize an API structure in ExpressJs for a system with numerous chapters containing various topics, each of which has its own

How should I design the API structure for a system with multiple chapters, each containing multiple topics and one PDF for each topic? I am working with Express. In my database, I have two tables - one for chapters and another for topics and their associa ...

Tips for disentangling code from types in Typescript

Instead of intertwining code and types like the example below: const compar8 : boolean | error = (action: string, n: number) => { switch(action) { case 'greater': return n > 8; case 'less': ...

The behavior of TypeScript class inheritance differs from that of its ES6 equivalent

I'm currently developing a custom error handling middleware for my node.js project using express and TypeScript. One key component of this middleware is the AppError class, which extends the built-in Error class. The code for this class is as follows: ...

Angular Material SnackBar not responding to the `onAction()` method

I'm encountering an issue with the Angular Material SnackBar's onAction() method. It seems that it is not triggering after the button is clicked. Even though I have subscribed to the onAction, afterDismissed, and afterOpened methods, only the lat ...

Encountering an issue following the update from Angular 8 to 12 - receiving the error message: "The 'controls' property is not present in the 'AbstractControl' type."

Previously, I had a fully operational code in Angular 8. Recently, I made the decision to upgrade from version 8 to Angular 12. The main feature of my project is a dynamic reactive form structured in a question-answer format. This form adapts based on the ...

How to Implement Angular ngStyle with ChangeDetectionStrategy.OnPush?

Check out this StackBlitz demonstration that demonstrates how ngStyle is being used to style the h1 element in the following way: <h1 [ngStyle]="{'background-color': backgroundColor}" The component named HelloComponent employs the O ...

Definition for the type react-navigation-v6 <Stack.Group>

I'm having trouble figuring out the proper type definition for a Stack group that includes screens (refer to TestStack.Group and the nested TestStack.Screen). The navigation stack: const TestStack = createNativeStackNavigator<TestStackParamList> ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

The generated code is unable to import the file compiled by Clasp

I am encountering an issue with my TypeScript files in my Google App Project. Here is a breakdown of my files: src/main.ts function main(): void { console.log('main'); hello(); } src/other.ts console.log('hello world'); ...

Can TypeScript automatically deduce object keys from function argument values?

Consider this function for parsing strings. const { a, b } = parseString({ string, mapping: [{ param: 'a', ... },{ param: 'b', ... }] Is there a way to restrict TypeScript to accept only &a ...

Listening for Internet Connection in Ionic and Angular

Currently, I am working on implementing a listener in my Ionic app that can detect changes in network activity and respond accordingly. import { Component } from '@angular/core'; import { Network } from '@capacitor/network'; @Component ...

Adjust the parameters and return types of TypeScript generic functions

Is it possible to make all the arguments of a function readonly and convert that function to an async function? For instance: declare function foo<T>(bar: T, baz: T[]): T; Transform into declare function foo<T>(bar: Readonly<T>, baz: re ...