React Error: “React.createElement: type is invalid” when using GluestackUI and Select Component

I am encountering the following error when running my React Native app:

ERROR  Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `ForwardRef`.
    in Unknown (created by RHFInput)
    in FocusScope
    in ActionsheetContentContextProvider
    in RCTView (created by View)
    in View (created by Animated(View))
    in Animated(View)
    in MotionComponent
    in Unknown (created by StyledSelectActionsheetContent)
    in StyledComponent
    in Unknown
    in RCTView (created by View)
    in View (created by Animated(View))
    in Animated(View)
    in Unknown (created by Select.Content)
    in Select.Content
    in RCTView (created by View)
    in View (created by StyledView)
    in StyledComponent
    in RCTView (created by View)
    in View (created by OverlayView)
    in OverlayView (created by OverlayContainer)
    in PortalProvider (created by GluestackUIProvider)
    in StyledProvider (created by GluestackUIStyledProvider)
    in GluestackUIStyledProvider (created by GluestackUIProvider)
    in GluestackUIProvider (created by NativeBaseProvider)
    in NativeBaseProvider (created by App)
    in ToastProvider (created by GluestackUIProvider)
    in PortalProvider (created by GluestackUIProvider)
    in StyledProvider (created by GluestackUIStyledProvider)
    in GluestackUIStyledProvider (created by GluestackUIProvider)
    in GluestackUIProvider (created by App)
    in App (created by RootApp)
    in ReactNativeProfiler (created by RootApp)
    in RCTView (created by View)
    in View (created by __Sentry.TouchEventBoundary)
    in __Sentry.TouchEventBoundary (created by RootApp)
    in RootApp (created by withDevTools(RootApp))
    in withDevTools(RootApp)
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)

I am using the following libraries and versions:

 "@gluestack-style/react": "^1.0.57",
 "@gluestack-ui/config": "^1.1.20",
 "@gluestack-ui/themed": "^1.1.61",
 "@gluestack-ui/themed-native-base": "^0.1.108",
 "react": "18.3.1",
 "react-native": "0.76.2",
 "expo": "^52.0.0",

I suspect the issue might be related to:

Incorrect imports (default vs named imports).
GluestackUI configuration or component usage.
Here’s how I am importing and using the component:

import {
  Select,
} from '@gluestack-ui/themed-native-base';

const App = () => (
  <Select>
     <Select.Item value="1">Option 1</Select.Item>
                <Select.Item value="2">Option 2</Select.Item>
  </Select>
);

I’ve double-checked my imports, but the error persists.

What I’ve tried:

Verified the imports for Select and its subcomponents.
Checked if any components are undefined.
Confirmed that GluestackUI is correctly set up with its provider.
Question: What could cause this error in this context, and how can I resolve it? Is there a specific configuration step or component usage pattern I might have missed?

p.s It appear after upgrade expo from 51 to 52 SDK

Axios returns 403 on API call but okhttp3 (java) works fine

I know that this question might be already answered, but I checked related questions, tried the solutions but could not get it to work.
Here is the issue:

Goal
Get JSON response from the following API: https://dev.epicgames.com/community/api/documentation/table_of_content.json?path=en-us/unreal-engine

Problem
My server (localhost) throws a 403 error.

Below you can see my code and what I already tried. I assume that it is amybe a CORS related issue but I was not able to find out more. Maybe you can help.
Many thanks in advance 🙂

Calling the API directly via Postman with a GET request works fine.

JS Code:

const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/fetch-epic-api', async (req, res) => {
    try {

        const response = await axios.get('https://dev.epicgames.com/community/api/documentation/table_of_content.json?path=en-us/unreal-engine', {
        headers: {
            'accept': 'application/json',
            'cache-control': 'max-age=0',
            'sec-fetch-site': 'cross-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
        },
        });


        res.json(response.data);
    } catch (error) {
        console.error('Fehler bei der API-Anfrage:', error);
        res.status(500).json({ error: 'Es gab einen Fehler bei der Anfrage.' });
    }
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server läuft auf http://localhost:${PORT}`);
});`

Terminal output:
AxiosError: Request failed with status code 403
at settle (C:DEV_HOMEToolstestJsnode_modulesaxiosdistnodeaxios.cjs:2019:12)
at BrotliDecompress.handleStreamEnd (C:DEV_HOMEToolstestJsnode_modulesaxiosdistnodeaxios.cjs:3135:11)
at BrotliDecompress.emit (node:events:530:35)
at endReadableNT (node:internal/streams/readable:1698:12)
at process.processTicksAndRejections (node:internal/process/task_queues:90:21)
at Axios.request (C:DEV_HOMEToolstestJsnode_modulesaxiosdistnodeaxios.cjs:4287:41)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async C:DEV_HOMEToolstestJsdiezweite.js:12:26 {
code: ‘ERR_BAD_REQUEST’,

When doing this in Java with okhttp3, it is working.
Java Code:

public static void main(String[] args) { 

OkHttpClient client = new OkHttpClient(); 
   Request request = new Request.Builder()
            .url("https://dev.epicgames.com/community/api/documentation/table_of_content.json?path=en-us/unreal-engine")
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            System.err.println("Fehler bei der API-Anfrage: " + e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();

                try {
                    JSONObject jsonObject = new JSONObject(responseBody);
                    System.out.println("Antwort von der API: ");
                    System.out.println(jsonObject.toString(2));
                } catch (Exception e) {
                    System.err.println("Fehler beim Parsen der Antwort: " + e.getMessage());
                }
            } else {
                System.err.println("Fehler bei der API-Anfrage, Statuscode: " + response.code());
            }
        }
    });
}`

how not to write routes for express node js application

I’m working on a Node.js/Express application, and as the project grows, I’m starting to run into issues with managing and registering routes in a centralized app.js file. Here’s how I’ve structured my project so far:

  1. I have an app/ folder with subfolders for different modules, such as
    auth, cart, shop, and admin.
  2. Inside each module, I have files like routes, controllers, services,
    repositories, etc.
  3. In the app.js file (which is centralized), I register all the module
    routes using app.use()

Problem: This setup works fine when the app is small, but as more routes and modules are added, registering all routes in app.js is becoming harder to maintain. The file is getting cluttered, and I feel it’s not the best practice as the app scales.

Question What’s the best way to organize and manage route registration in a growing Node.js/Express application? Should I consider dynamically loading routes or implementing some sort of route centralization strategy to keep app.js clean and maintainable? Any recommendations or best practices for structuring routes in larger Express apps?

app.js

const express = require('express');
const app = express();
const connectDB = require('./config/database');
const authRoutes = require('./app/auth/routes/authRoutes');

app.use(express.json());

connectDB();

app.use('/api/authenticate', authRoutes);

module.exports = app; 

index.js

require('dotenv').config();
const config = require('./config/envConfig');
const logger = require('./utils/logger');
const app = require('./app'); 

const PORT = config.port || 5000;

app.get('/', (req, res) => res.status(200).send('HELLO WORLD!'));

// Error Handling
app.use((err, req, res, next) => {
  logger.error(`Error: ${err.message}`);
  res.status(500).json({ message: 'Internal Server Error', error: err.message });
});

app.all('*', (req, res) => res.status(404).json({ message: 'No Matching Route' }));


// Start the server
app.listen(PORT, (err) => {
  if (err) {
    logger.error(`Error starting server: ${err.message}`);
    process.exit(1); // Exit the process if the server fails to start
  }
  logger.info(`Server running on port ${PORT}`);
});

Why does AsyncStorage.getItem throw Cannot read property ‘getItem’ of undefined in a React Native app when used via a shared npm package?

I’m building a modular system consisting of multiple npm packages for React and React Native projects. Here’s the setup:

  1. replyke-core:

    • Contains shared logic for React and React Native.
    • Includes a conditional getAsyncStorage function to dynamically import @react-native-async-storage/async-storage only when used in React Native.
  2. replyke-rn:

    • A React Native-specific package that consumes replyke-core.
  3. Final consuming project:

    • A React Native app consuming replyke-rn.

Problem

In the final consuming project, calling AsyncStorage.getItem directly works without issue, but when I use it indirectly through replyke-core, it throws the following error:

(NOBRIDGE) ERROR Cannot read property 'getItem' of undefined


Implementation

In replyke-core, I have the following refreshToken function in my authentication context:

const refreshToken = useCallback(async () => {
  try {
    const path = `/auth/refresh`;

    let refreshToken = null;

    // Use helper function to dynamically load AsyncStorage
    if (isReactNative()) {
      const AsyncStorage = await getAsyncStorage();
      console.log("Using AsyncStorage:", AsyncStorage);

      if (!AsyncStorage) {
        console.error("Failed to retrieve AsyncStorage, skipping refresh.");
        return;
      }

      console.log("Checking getItem type:", typeof AsyncStorage.getItem);
      if (typeof AsyncStorage.getItem !== "function") {
        throw new Error("AsyncStorage.getItem is not a function.");
      }

      refreshToken = await AsyncStorage.getItem("refreshToken");
      console.log("Retrieved refreshToken:", refreshToken);

      if (!refreshToken) {
        console.log("No refresh token found.");
        return;
      }
    }

    const response = await axios.post(
      path,
      isReactNative()
        ? { projectId, refreshToken } 
        : { projectId },
      { withCredentials: !isReactNative() }
    );

    const { accessToken: newAccessToken, user: newUser } = response.data;
    setAccessToken(newAccessToken);
    setUser(newUser);
    return newAccessToken;
  } catch (err) {
    handleError(err, "Refresh error: ");
  }
}, [projectId]);

useEffect(() => {
  const fetchInitial = async () => {
    await refreshToken();
    setLoadingInitial(false);
  };
  fetchInitial();
}, [projectId]);

This function uses a helper function to dynamically load AsyncStorage:

export async function getAsyncStorage() {
  try {
    const module = await import("@react-native-async-storage/async-storage");

    const AsyncStorage = module.default;

    if (!AsyncStorage) {
      throw new Error("AsyncStorage is not defined.");
    }
    if (typeof AsyncStorage.getItem !== "function") {
      throw new Error("AsyncStorage.getItem is not a function.");
    }

    return AsyncStorage;
  } catch (err) {
    console.error("Error loading AsyncStorage:", err);
    return null;
  }
}

The @react-native-async-storage/async-storage package is declared as a peerDependency in both replyke-core and replyke-rn:

"peerDependencies": { "@react-native-async-storage/async-storage": "1.x" }

And it is installed in the final consuming project:

npm install @react-native-async-storage/[email protected]


Observations

  1. Direct Usage in the Final Project Works: When I test AsyncStorage directly in the final consuming project, it works as expected:
useEffect(() => {
      const test = async () => {
        const value = await AsyncStorage.getItem("my-key");
        console.log({ value }); // Logs: { value: null }
      };
      test();
    }, []);
  1. Dynamic Import Logs: When debugging the logs show that AsyncStorage is resolved correctly and getItem is a function (identical when using dynamic or static imports):
(NOBRIDGE) LOG  Using AsyncStorage: { clear: [Function clear], getItem: [Function getItem], ... }
(NOBRIDGE) LOG  Checking getItem type: function

But the call to getItem still fails:

(NOBRIDGE) ERROR Cannot read property 'getItem' of undefined

  1. Static Import Fails Too: To rule out dynamic imports as the issue, I replaced getAsyncStorage with a static import in replyke-core:
import AsyncStorage from "@react-native-async-storage/async-storage";
    
refreshToken = await AsyncStorage.getItem("refreshToken");

The same error occurs.

  1. When I Remove the refreshToken Function Call: Removing the useEffect that calls refreshToken stops the error.

What I’ve Tried

  1. Used .then/.catch Instead of await:
    I refactored the refreshToken function to use a .then/.catch chain for handling the getAsyncStorage promise, as it could potentially affect scoping or execution context. The AsyncStorage object resolved correctly, and getItem was still confirmed to be a function, but the same error (Cannot read property ‘getItem’ of undefined) occurred when calling getItem.
  2. Declaring @react-native-async-storage/async-storage as a peerDependency in both replyke-core and replyke-rn.
  3. Verifying that the final consuming project has the dependency installed (1.23.1).
  4. Using both dynamic and static imports in replyke-core.
  5. Running npm dedupe to ensure no duplicate versions of @react-native-async-storage/async-storage exist.
  6. Adding extensive logging to confirm that AsyncStorage and its methods are resolved correctly.

Environment

  • React Native: 0.76.2
  • Expo: 52.0.7
  • AsyncStorage: 1.23.1

Question

Why does AsyncStorage.getItem throw Cannot read property 'getItem' of undefined when used through the replyke-core package, but works correctly when used directly in the consuming project? How can I resolve this issue?

VS Code view js console output when browser dev tools is disabled?

Background: I teach basic web development in a high school. Our technology department has disabled developer tools on all web browsers for student accounts after a recent cyber attack. I need a workaround to allow students to see console output that can be implemented without installing any additional software for two basic scenarios.

Scenario #1: Using VS Code web through a Github codespace. I could swear that I found an extension at one point that would show console output, but I haven’t been able to locate it again. All the ones I have tried are dependent on browser dev tools being available.

Scenario #2: Using an online platform such as CodeHS, code.org, etc. Maybe there’s a website out there that simulates developer tools? I haven’t been able to find anything that will work.

Any advice on how to get students access to something like dev tools without dev tools would be greatly appreciated.

Trading Commodities price API [closed]

How I can get Trading Commodities price API?
I can’t find commodities future prices .Are there any other API available besides CME.
The main Nasdaq future and mini Hang Seng future price API can’t be found. I try but it is difficult for me.

cors error and no separate backend server code [duplicate]

I do not have a separate server code and I keep getting a cors error.
I have the below code:

muggle_process.js file:

let url = "https://favqs.com/api/qotd";

let saveButtonElement = document.querySelector("#save-username");
let nameInputElement = document.querySelector("#username");
let welcomeMessage = document.querySelector("#welcome-message");
let quoteOfTheDay = document.querySelector("#quote-of-the-day");
let author = document.querySelector("#author");

saveButtonElement.addEventListener("click", function () {
  let name = nameInputElement.value;
  if (name.length < 2) {
    quoteOfTheDay.innerText = "";
    welcomeMessage.innerHTML = "Please enter at least 2 letters.";
  }
  else {
    nameInputElement.value = "";
    welcomeMessage.innerText = `Welcome, ${name}!`;
    fetchingQuote();
  }
});

function fetchingQuote() {
  fetch(url)
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      quoteOfTheDay.innerHTML = "<label>Quote of the day</label><br>" + data.quote.body;
      author.innerHTML = "---" + data.quote.author;
    })
    .catch((err) => {
      alert("Error: " + err);
      console.log("Error", err);
    });
}

document.getElementById("go-back").onclick = function () {
  location.href = "welcome.html";
};

document.addEventListener("keyup", function (event) {
  if (event.key === "Enter") {
    saveButtonElement.click();
    nameInputElement.value = "";
  }
});

When I run the code, I keep getting the below error in my console browser:

Access to fetch at 'https://favqs.com/api/qotd' from origin 'http://127.0.0.1:5500' has been 
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested 
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to 
fetch the resource with CORS disabled.

I also tried adding headers “Access-Control-Allow-Origin“, but still keep getting the cors error. How can I fix this error?

My file structure is as below for the application:

file structure of application

How can I determine if a respondent’s email address is unique in a list?

Overview: A Google Sheets file is linked to 3 Google Forms. After a form is submitted, the responses are added to the coinciding Dummy spreadsheet tabs:
Form Responses 1
Form Responses 2
Form Responses 4

After each form submission, email addresses are being tracked (column B), in addition to other responses from the form’s questions.

Goal: My goal is to identify if a respondents email address is unique within all 3 Form Responses tab.

For example, the preferred result would only display one email address if it is listed in multiple Dummy Sheet tabs.

The Email addresses are being tracked in column B of the Dummy Spreadsheet. After this validation takes place, subsequent functions will be executed.

Current issue: The current logic is identifying the Unique email addresses per sheet tab, but not a cumulative result (i.e. for all tabs combined). The preferred result would only display one email address if it is listed in multiple Dummy Sheet tabs.

Further guidance would be much appreciated.

function findUnique(){
  var col = 1 ; // column B (Email Address)
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array listing sheets to exclude from execution
  var exclude = ["Reference","Index"];

 for (var s in allsheets){
 var source_sheet = allsheets[s];   

    // Stop iteration execution; exclude Reference and Index tabs.
  if(exclude.indexOf(source_sheet.getName()) != -1) continue;

  var data=source_sheet.getDataRange().getValues();// get all data
  //Logger.log(data);
  var newdata = new Array();
  for(nn in data){
    var duplicate = false;
    for(j in newdata){
  
      if(data[nn][col] == newdata[j][0]){
        duplicate = true;
      }
    }

    if(!duplicate){
      newdata.push([data[nn][col]]);
    }
  
  }
Logger.log(newdata);
  newdata.sort(function(x,y){
  var xp = Number(x[0]);// ensure you get numbers
  var yp = Number(y[0]);
  return xp == yp ? 0 : xp < yp ? -1 : 1;// sort on numeric ascending
});
//Logger.log(newdata); // Uniques?
  }
}

Dummy Spreadsheet

enter image description here

Uncaught ReferenceError: Function is not defined at HTMLButtonElement.onclick

I have one issue.

I have function add() on buttons with number parameter. So when I click button in console there error Uncaught ReferenceError: add is not defined at HTMLButtonElement.onclick

This is my code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .calculator{
            display: flex;
        }
        button:not(.big):not(.button-c) {
            width: 38.5px;
            height: 38px;
            font-size: 16px; 
            padding: 5px;  
            border: none;
            background-color: #f0f0f0;
            cursor: pointer;
        }
        #calc-input{
            height: 25px;
        }
        td[rowspan="2"] button {
            width: 38.5px;  
            height: 79px;
            font-size: 16px;
            padding: 5px;  
            border: none;
            background-color: #f0f0f0;
            cursor: pointer;
        }
        td[colspan="2"] button {
            height: 38px;  
            width: 100%;
            font-size: 16px; 
            padding: 5px;  
            border: none;
            background-color: #f0f0f0;
            cursor: pointer;
        }
        .button-c{
            background-color: rgb(255, 51, 0);
            width: 38.5px;
            height: 38px;
            font-size: 16px; 
            padding: 5px;  
            border: none;
            cursor: pointer;
        }
    </style>
    
</head>
<body>
    <div class="calculator">
        <input add="text" id="calc-input">
    </div>
    <table>
        <tr>
            <td><button class="button-c">C</button></td>
            <td><button><i class="fas fa-backspace"></i></button></td>
            <td><button>/</button></td>
            <td><button>*</button></td>
        </tr>
        <tr>
            <td><button onclick="add(7)">7</button></td>
            <td><button onclick="add(8)">8</button></td>
            <td><button onclick="add(9)">9</button></td>
            <td><button>-</button></td>
        </tr>
        <tr>
            <td><button onclick="add(4)">4</button></td>
            <td><button onclick="add(5)">5</button></td>
            <td><button onclick="add(6)">6</button></td>
            <td><button>+</button></td>
        </tr>
        <tr>
            
            <td><button onclick="add(1)">1</button></td>
            <td><button onclick="add(2)">2</button></td>
            <td><button onclick="add(3)">3</button></td>
            <td rowspan="2"><button class="big">=</button></td>
        </tr>
        <tr>
            <td colspan="2"><button class="big" onclick="add(0)">0</button></td>
            <td><button>.</button></td>
        </tr>
    </table>
    <script>
document.addEventListener("DOMContentLoaded", function() {
console.log("Script connected correctly");

function add(num) {
    console.log(num)
}
});
    </script>
</body>
</html>

What I have tried:

1)Placed the tag at the bottom of the body (just before the closing tag) to make sure the HTML elements are loaded before the JavaScript is executed.
2)Checked the browser console, and confirmed that console.log(“Script connected correctly”) is printed, indicating the script is loaded.
3)Tried other solutions such as using DOMContentLoaded event, but the error persists.

What I expect: I expect that when I click a number button (e.g., 7), the type() function should be called, and the number should be appended to the input field.

Can anyone help me understand why type() is not recognized as a function, even though it’s clearly defined in the external script.js file?

How to correctly type useTemplateRefsList in a recursive component in Vue 3?

I’m working on a recursive Vue 3 component using the Composition API and the useTemplateRefsList function from @vueuse/core.

My goal is to collect references to each instance of the recursive component. However, I’m struggling to type the list of references correctly, as the this keyword is not available in the Composition API.

Here’s a simplified version of my setup:

// toto.vue
<template>
  {{ data.name }}
  <toto 
   v-for="item in data.children"
   ref="childRefs"
   :key="item.id"
   :data="item.children"
  />
</template>

<script setup lang="ts">
import { useTemplateRefsList } from '@vueuse/core';

const { data } = defineProps<{
  id: string;
  name: string;
  children?: [
   {
     id: string;
     name: string,
     children?: [...]
   }
  ]
}>();

// Attempting to type the refs list
const childRefs = useTemplateRefsList</* What type goes here? */>();
</script>

Problem

I want to type childRefs such that it correctly represents an array of the recursive component’s instances.

Since this is unavailable in the script setup syntax, I cannot directly refer to the component’s instance type.

What I’ve tried

  1. Using ComponentPublicInstance:
const refs = useTemplateRefsList<ComponentPublicInstance>();

But this type is too generic and doesn’t reflect the actual instance of the recursive component.

  1. Using InstanceType:
const refs = useTemplateRefsList<InstanceType<typeof RecursiveComponent>>();

However, RecursiveComponent isn’t defined yet during its own declaration, which creates a circular dependency issue.

  1. Typing via expose

I considered using defineExpose to expose properties/methods and type against those, but this feels like overkill for a simple recursive component.

  1. Export type from another ts file
// definitionsFile.ts
import Toto from './Toto.vue';

// Without using an object, I get the following error: Type alias 'TotoType' circularly references itself.
export type TotoType = { a: InstanceType<typeof PermissionSummaryRow> };
// toto.vue
import Toto from './Toto.vue';

// 'childRefs' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer
const childRefs = useTemplateRefsList<TotoType['a']>();

// any
const test = childRefs.value[0]!;

Question

What is the correct way to type useTemplateRefsList for a recursive component in Vue 3? Is there a way to dynamically reference the current component’s type, or is there a workaround to achieve this?

Any help or guidance would be appreciated!

Firebase Functions – Missing events logging after third request

Currently we have a Firebase function responsible to listen for ‘xyz_event’.

When this event is sent from both Android/IOS, after the third submission we are still able to see the events (4th, 5th…) , coming on the analytics debug view. However, the event is not triggering the firebase function.
Once the function is triggered it should create a log with the payload
It just starts to trigger the function and create the logs again after 5 minutes.

Just thinking if there is a batch loading on Firebase SDK when submit the events or some setting on firebase to aggregate those events to prevent duplication.

event-functions.ts

import * as functions from 'firebase-functions';
import { Constants } from './assets/constants';
import { eventProcessor } from './event-processor';

export const screenView = functions
  .runWith({
    secrets: [
      Constants.FUNCTIONS_SETTINGS.SECRETS.SERVICE.CLIENTKEY,
      Constants.FUNCTIONS_SETTINGS.SECRETS.SERVICE.CLIENTSECRET,
    ],
  })
  .region(Constants.FUNCTIONS_SETTINGS.REGION.EUROPE)
  .analytics.event('footer_click')
  .onLog(async (event) => {
    await eventProcessor.submitEvent(Constants.TYPE.VIEW, event);
    return null;
  });

event-processor.ts

import * as functions from 'firebase-functions';
import { AnalyticsEvent } from 'firebase-functions/v1/analytics';
import { buildEventRequestHandler } from './handlers/build-event-request-handler';
import { logging } from './initApp';

const log = logging.log('EventProcessor');

const METADATA = {
  resource: {
    type: 'cloud_function',
    labels: {
      function_name: 'submitEvent',
    }
  }
};

class EventProcessor {
  public async submitEvent(eventType: string, eventPayload: AnalyticsEvent) {
    const firebaseId = eventPayload?.user?.appInfo?.appInstanceId;
    const user = eventPayload?.user;

    const logData = {
      eventType,
      eventPayload
    };

    log.info(log.entry(METADATA, logData));

This line should create the log and after the third request it’s not being logged.

log.info(log.entry(METADATA, logData));

How can I efficiently debounce a search input with async calls in JavaScript?

I’m building a search feature in a web application using vanilla JavaScript, where users type in a search query, and the app sends an asynchronous API request after a delay, to avoid excessive calls while the user is typing.

I want to debounce the input so that the API is only called after the user has stopped typing for a specified time (e.g., 500ms), but I also need to handle the asynchronous nature of the API calls efficiently.

const searchInput = document.getElementById('search-input');
let timeoutId;

searchInput.addEventListener('input', function(event) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
    searchAPI(event.target.value);
}, 500);
});

async function searchAPI(query) {
const response = await fetch(`https://api.example.com/search?q=${query}`);
const results = await response.json();
console.log(results);
}

How can I improve this code to ensure that:

Only one request is sent after the user has stopped typing for the specified delay.
If a new input comes in before the timeout expires, the previous request is canceled.
The solution is efficient, considering both performance and network usage.
I’d appreciate any suggestions for optimizing this debounce function while keeping it simple and working well with async/await.

Thanks in advance!

Not able to get proper Data in the excel file created using ExcelJS package in NodeJS

so i trying to create a xlx file from the input and upload it to S3 bucket so
when i pass large data say 1000 rows I could see that only column headers are created in the file not the data but still the file size is around 100kb
but if i send small input i could see the rows getting created

any help is much appreciated
attaching the snippet of the code where i am trying to create xlsx file

 await Promise.all(
      payload.queryResults.map(async (queryResult: QueryResult) => {
        const { columnHeader, strId, queryName, data = [] } = queryResult; 

        try {
          // Process the Excel file
          const workbook = new ExcelJS.Workbook();
          const worksheet = workbook.addWorksheet('Sheet1');
         
          worksheet.addRow(columnHeader);
          // Add data rows only if `data` is a non-empty array
          if (Array.isArray(data) && data.length > 0) {
            data.forEach((row) => {
              const rowData = columnHeader.map(col => row[col] || '');
              worksheet.addRow(rowData);
            });
          }

          const filePath = filename.xlsx`;
          const buffer = await workbook.xlsx.writeBuffer();

          await uploadFiletoS3(stagingBucket, filePath, Buffer.from(buffer));
          successfulQueries.push({ queryName, strId });
        } catch (uploadError) {
          failedQueries.push({ queryName, strId, error: uploadError.message });
          logger.error(`Error uploading file for query: ${queryName} for store: ${strId}`, { error: uploadError });
        }
      })
    );

JavaScript error: on button element, click is not a function?

I’m having issues with JavaScript not detecting the click event on a button. Here is my HTML code:

<input type="button" value="Upload" id="filemanagement_uploadbutton[0]" name="filemanagement_uploadbutton" onclick="javascript:uploadFiles();">

Here is my JavaScript code (with console.log commands for error checking):

let fileButtons = document.getElementsByName('filemanagement_uploadbutton');
console.log(fileButtons.length);          //returns 2, since I have two buttons
console.log(fileButtons[0].id);           //returns filemanagement_uploadbutton[0]
console.log(fileButtons[0].type);         //returns button
console.log(fileButtons[0].click);        //returns javascript:uploadFiles();
fileButtons[0].click();

I’ve also tried:

let fileButton = document.getElementsByName('filemanagement_uploadbutton')[0];
fileButton.click();

Both of these result in the error:

Uncaught TypeError: fileButtons[0].click is not a function

or

Uncaught TypeError: fileButton.click is not a function

How is it telling me that click is not a function on the element that it’s telling me the click function is “javascript:uploadFiles();” literally one element above?

Any insights? Thanks!

How to iterate over Array of objects and push to new array and also remove duplicate entries [closed]

I am trying to iterate over array of objects and remove duplicate entries while pushing to new array if any duplicates in nested array and form a flat array with same key value pair by just removing duplicate key. Can any one help please with below data set.

Json sample (Here Id is duplicate key):

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "moreDetails": {
      "items": [
        {
          "Id": "123",
          "City": "BLR",
          "State": "KA"
        }
      ]
    }
  }
]

Above json can be repeated like this also with any number:

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "moreDetails": {
      "items": [
        {
          "Id": "123",
          "City": "BLR",
          "State": "KA"
        }
      ]
    }
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "moreDetails": {
      "items": [
        {
          "Id": "12345",
          "City": "KAN",
          "State": "UP"
        }
      ]
    }
  }
]

Output trying to achieve is by removed duplicate key which is Id:

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "City": "BLR",
    "State": "KA"
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "City": "KAN",
    "State": "UP"
  }
]