typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet:

import type { NextApiRequest, NextApiResponse } from "next";
import { getMessaging } from "firebase-admin/messaging";

export default async function handler(req,res) {
  try{
    let { title, text, topic, condition, token } = req.body;
    topic === "" ? (topic = null) : "";
    condition === "" ? (condition = null) : "";
    token === "" ? (token = null) : "";
    const result = await getMessaging().send({
      notification: {
        title: title,
        body: text,
      },
      topic: topic,
      condition: condition,
      token: token,
    });
    res.status(200).send(result);
  } catch (err) {
    res.status(500).send(err);
  }
}

Do you have any suggestions for improving this implementation? I feel like there might be room for enhancement.

    topic === "" ? (topic = null) : "";
    condition === "" ? (condition = null) : "";
    token === "" ? (token = null) : "";

Answer №1

Instead of implementing a conditional assignment within a ternary expression, I prefer utilizing a function:

function replaceEmptyWithValue(value: string): string | null {
  return value === '' ? null : value;
}

This approach enhances the readability of your code when used in multiple instances:

topic = replaceEmptyWithValue(topic);
condition = replaceEmptyWithValue(condition);
token = replaceEmptyWithValue(token);

Answer №2

This code snippet contains a syntax error:

topic === "" ? (topic = null) : "";
condition === "" ? (condition = null) : "";
token === "" ? (token = null) : "";

A corrected version could be:

topic = (topic === "") ? null : "";
condition = (condition === "") ? null : "";
token = (token === "") ? null : "";

However, the purpose of this block of code is not entirely clear.

If your intention is to assign null to variables with empty strings, you can simplify it like so:

if (topic === "") topic = null;
if (condition === "") condition = null;
if (token === "") token = null;

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

Anticipated the server's HTML to have a corresponding "a" tag within it

Recently encountering an error in my React and Next.js code, but struggling to pinpoint its origin. Expected server HTML to contain a matching "a" element within the component stack. "a" "p" "a" I suspect it may be originating from this section of my c ...

What could be causing SVG to not render in a NEXTJS project upon deployment on Vercel?

Recently, I created a standout single-page nextJS application that was beautifully styled with Tailwind CSS. One interesting feature I added was incorporating the background of a component called SectionWrapper as an svg file. To achieve this, I crafted a ...

Encountering a 404 Error while using GetStaticPaths in NextJs

Having issues with Next JS dynamic routes resulting in a 404 Error. Initially attempted debugging by setting it up dynamically, then manually at http://localhost:3001/question/62e7b69ca560b1c81aa1a853 but still encountering the same issue. Tried toggling f ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Creating adaptable rows and columns with Angular Material's data table feature

My approach to rendering dynamic rows and columns using a basic table was successful: <tbody> <tr *ngFor="let row of data"> <td *ngFor="let val of row"> {{ val }} </td> </tr> </tbody> </ ...

When utilizing a custom hook that incorporates useContext, the updater function may fail to update as

After developing a customized react hook using useContext and useState, I encountered an issue where the state was not updating when calling the useState function within the consumer: import { createContext, ReactNode, useContext, useState, Dispatch, SetSt ...

Utilize decorators for enhancing interface properties with metadata information

Can decorators be utilized to add custom information to specific properties within an interface? An example can help clarify this: Interface for App state: export interface AppState { @persist userData: UserData, @persist selectedCompany: UserCo ...

The term 'Pick' is typically used to identify a specific type, however, in this particular situation, it appears to be functioning as a value while attempting to expand the Pick

I'm attempting to selectively expose certain properties from an ancestor class on my descendant class. My approach involves using the Pick utility in TypeScript. export class Base { public a; public b; public c; } export class PartialDes ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

Creating an interface for React props

Hey everyone, I'm facing an issue and need some advice. I prefer using interfaces to maintain readability and utilize intellisense in my code. However, I'm struggling with implementing this approach when working with data passed through props. H ...

What is the best way to determine the type of `rootReducer`?

My project is set up with a combination of React, Redux, Immutable.js, and TypeScript. As I worked on implementing it, I made an effort to declare types wherever possible which led me to discover an interesting issue. A code example illustrating the proble ...

Display JSON data in a table format using Angular

I have received a JSON result that looks like this: { "discipline":"ACLS", "course": [ { "value":"ACLS Initial", "classes":"0", "students":"0" }, { "BLS":"CPR Inst ...

What steps can I take to resolve the "Unable to call a potentially 'undefined' object" error?

I'm currently working with CreateContext in Typescript and I have encountered a problem in the code that I can't seem to resolve. I am trying to use typesafe TX to provide state and dispatch (via useReducer) in a component hierarchy. Here is the ...

Is there a workaround in TypeScript to add extra details to a route?

Typically, I include some settings in my route. For instance: .when('Products', { templateUrl: 'App/Products.html', settings: { showbuy: true, showex ...

MXGraph has an issue where edges fail to be redrawn after being moved

Perhaps this question may seem trivial, but I am facing an issue in my code and seeking guidance from the community. I am working on a javascript mxGraph application within Angular7. Specifically, I have modified the ports.html example for my project. Wh ...

Receiving intelligent suggestions for TypeScript interfaces declared within function parameters

Here is a simple example I put together: In this example, intellisense provides suggestions for the interface of the object named test in the foo function. It works perfectly and I love it! However, if you declare that interface somewhere else like this: ...

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

Different categories of properties within a generic function

I'm attempting to modify certain fields of my object using field names. Here is the code snippet I have written: interface Foo { a: number[], b: string[], } type Bar = { [T in keyof Foo] : (arg : Foo[T]) => Foo[T] } function test<T ex ...

Different Approaches to Authentication in Next.js

I've been working on establishing a secure authentication process for my Next.js project, but I'm feeling quite lost at the moment. Despite referencing the examples in the Next.js repository, I still have numerous queries regarding a comprehensiv ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...