Is it okay to allows CORS for all when using Vercel to host?

I am trying to implement an API from a external source. Is it okay to use * to allow any or is it better to specify the domain?
I am curios in terms of security and if this only means that external APIs are allowed only from my code?

{
      "src": "/.*",
      "headers": {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,POST,PUT,DELETE,OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type, Authorization"
}

I have tried to look online if there are anyone else asking this question.

Most basic setup for SSR with React 19 and renderToPipableStream api

I have looked at a lot of online examples, but most of them appear to be setup with React 18 – although the api seems the same.

Anyways, I have created the following setup:

enter image description here

The full code is on GitHub here: https://github.com/uninstallit/basic-ssr

To run it:

pnpm install
pnpm run build
pnpm run start

Open browser at http://localhost:4000

I have tried many variations of the server but with similar negative results. Here is my server main handler:

app.use(express.static(path.resolve(__dirname, "public")));

app.get("/", (request, response) => {
  console.log("request: ", request.url);

  const { pipe } = renderToPipeableStream(<App />, {
    bootstrapScripts: ["main.js"],
    onShellReady() {
      response.setHeader("content-type", "text/html");
      pipe(response);
    },
    onError(err) {
      console.error(err);
      res.status(500).send("Internal Server Error");
    },
    onShellError() {
      response.statusCode = 500;
      console.log("shell err out");
      response.send("<!doctype html><p>Loading...</p>");
    },
  });
});

When I open the page – I get hydration errors that point to the injected App code.

enter image description here

Can someone please take a look and give me a hint where I went wrong? Or maybe check if this runs on another computer.

How do I get my text element to change with my javascript file function? [duplicate]

I am trying to get my button to display input values when it is clicked.However it seems to be unresponsive. Any tips, tricks, or ideas to help.I don’t want to use script tag in html page. I only want to use the external JS file that is linked to the top of the page.

Here is my JavaScript File.

const myButton = document.getElementById("buttonQuery");
myButton.addEventListener(click, QueryButton());

function QueryButton() {
  const fName = document.getElementById("FirstName").value;
  const lName = document.getElementById("LastName").value;
  const userEmail = document.getElementById("Email").value;
  const userPhoneNumber = document.getElementById("Phone").value;
  const userAge = document.getElementById("Age").value;
  const nameUser = document.getElementById("userName").value;
  const pWord = document.getElementById("passWord").value;

  document.getElementById("firstNamePara").innerHTML = fName;
  document.getElementById("emailPara").innerHTML = lName;
  document.getElementById("phonePara").innerHTML = userEmail;
  document.getElementById("userPara").innerHTML = userPhoneNumber;
  document.getElementById("agePara").innerHTML = userAge;
  document.getElementById("userNamePara").innerHTML = nameUser;
  document.getElementById("passwordPara").innerHTML = pWord;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>HTML + CSS</title>
    <link rel="stylesheet" href="styles.css" />
    <script src="script.js"></script>
  </head>
  <body>
    <!--The first form element has been created for you-->
    <!--Complete the rest of the assignment as outlined-->
    <form>
      <label for="firstName">First Name:</label>
      <input id="FirstName" type="text" />
    </form>

    <form>
      <label for="LastName">Last Name:</label>
      <input id="LastName" type="text" />
    </form>

    <form>
      <label for="Email">Email:</label>
      <input id="Email" type="email" />
    </form>

    <form>
      <label for="Phone">Phone</label>
      <input id="Phone" type="tel" />
    </form>

    <form>
      <label for="Age">Age</label>
      <input id="Age" type="number" />
    </form>

    <form>
      <label for="userName">UserName</label>
      <input id="userName" type="text" />
    </form>

    <form>
      <label for="Password">Password</label>
      <input id="Password" type="password" />
    </form>

    <form>
      <label for="ConfirmPassword">Confirm Password</label>
      <input id="confirmPassword" type="password" />
    </form>
    <button id="buttonQuery" type="button">Submit Query</button>
    <p id="firstNamePara"></p>
    <p id="lastNamePara"></p>
    <p id="emailPara"></p>
    <p id="phonePara"></p>
    <p id="agePara"></p>
    <p id="userNamePara"></p>
    <p id="passwordPara"></p>
  </body>
</html>

Any tips or tricks to optimize this?

React child component causes parent state items to be deleted

The Goal

I am wrapping a list of message items with a component ‘ListWrap’.This component is designed to wrap each item in the list and detect when the children items are added or removed from the list. It displays all items even if removed from the parent components list and just changes the color of the wrapper red for removed or green for added.

There is a greater purpose for this, but for demonstrating the problem I am simply adjusting the wrapper color.

The Problem

The problem Im facing is that when removing items that are not the last item in the list, it also removes all the subsequent items. So for example from 3 items, if item 2 is selected to be removed, then item 2 and 3 are removed.

Im not sure why this is because when removing the ListWrap component the list functions fine. When using ListWrap and passing the prop children directly to the return statement it works fine. But when I attempt to return a modified selection of children then the issue occurs. I have noticed that the parent messages state is directly effected by this so it appears some logic on the child element is causing the deletion of the extra list items even though only one is selected to be deleted.

Codesandbox example

Example provided shows that when clicking on a items close/remove button, the expected behaviour is it should only make that wrapper red (left colored box), not all the items below.

Test.js

import React, { useState } from "react";
import ListWrap from "./ListWrap";

const Test = () => {
  const [messages, setMessages] = useState([]);

  const addMessage = () => {
    const id = Date.now();
    setMessages([...messages, { id: id, text: `Message ${id}` }]);
  };

  const removeMessage = (id) => {
    setMessages(messages.filter((message) => message.id !== id));
  };

  return (
    <div className="container mx-auto p-4">
      <div className="mb-4 flex justify-between">
        <button
          onClick={addMessage}
          className="rounded bg-green-500 px-4 py-2 text-white hover:bg-green-600 focus:outline-none"
        >
          Add New
        </button>
        <button
          onClick={() => setMessages(messages.slice(0, -1))}
          className="rounded bg-orange-500 px-4 py-2 text-white hover:bg-orange-600 focus:outline-none"
        >
          Remove Last
        </button>
        <button
          onClick={() => setMessages([])}
          className="rounded bg-red-500 px-4 py-2 text-white hover:bg-red-600 focus:outline-none"
        >
          Remove All
        </button>
      </div>

      <div className="space-y-2">
        <ListWrap>
          {messages.map((message) => (
            <div
              key={message.id}
              className="relative rounded bg-gray-500 p-4 text-white shadow-lg"
            >
              <p>{message.text}</p>
              <button
                onClick={() => removeMessage(message.id)}
                className="absolute right-0 top-0 mr-2 mt-2 rounded bg-red-500 px-2 py-1 text-white hover:bg-red-600 focus:outline-none"
              >
                X
              </button>
            </div>
          ))}
        </ListWrap>
      </div>
    </div>
  );
};

export default Test;

ListWrap.js

import React, { useState, useEffect } from "react";

const ListWrap = ({ children }) => {
  const [allChildrenItems, setAllChildrenItems] = useState([]);

  useEffect(() => {
    const newChildren = React.Children.toArray(children);
    const newChildrenKeys = newChildren.map((child) => child.key);
    const currentChildrenKeys = allChildrenItems.map((item) => item.child.key);
    const addedChildrenKeys = newChildrenKeys.filter(
      (key) => !currentChildrenKeys.includes(key)
    );
    const removedChildrenKeys = currentChildrenKeys.filter(
      (key) => !newChildrenKeys.includes(key)
    );

    const updatedChildrenItems = [
      ...allChildrenItems.map((item) => {
        if (removedChildrenKeys.includes(item.child.key))
          return { ...item, isActive: false };
        return item;
      }),
      ...newChildren
        .filter((child) => addedChildrenKeys.includes(child.key))
        .map((child) => ({ child, isActive: true })),
    ];

    setAllChildrenItems(updatedChildrenItems);
  }, [children]);

  //Using a custom item based on the children data IS causing issue with parent messages state:
  return (
    <div>
      {allChildrenItems.map((item) => (
        <div key={item.child.key}>
          <div
            className={
              item.isActive
                ? "mb-2 pl-10 z-50 bg-green-500"
                : "mb-2 pl-10 z-50 bg-red-500"
            }
          >
            {item.child}
          </div>
        </div>
      ))}
    </div>
  );
  //Using children directly from prop NOT causing issue with parent messages state:
  //   return (
  //     <>
  //       {children.map((item) => (
  //         <div key={item.key}>
  //           <div className={item.isActive ? "active" : "inactive"}>{item}</div>
  //         </div>
  //       ))}
  //     </>
  //   );
  // };
};

export default ListWrap;

How can I add a button directly inside the calendar in AngularJS?

I am trying to add a button inside a calendar input component (datepicker) in AngularJS, but I haven’t been successful yet.

Here is the code I am using:

<div class="input-group date-picker-aligned">
 <input type="month" class="form-control" id="input_competencia" name="competencia"
    ng-model="prestadoresCtrl.formFilterPrestCtrl.competencia"
    blur="prestadoresCtrl.isDataCompetenciaValida()"
    is-open="prestadoresCtrl.isOpenDateCompetencia" uib-datepicker-popup
    datepicker-options="datepickerOptions" required autofocus
    ng-change="prestadoresCtrl.filterDate()" />
 <div class="input-group-addon mouse-action"
    ng-click="prestadoresCtrl.openDateSolic('Competencia')">
    <i class="fas fa-calendar</i>
 </div>
</div>

Local Configuration:

this.$scope.datepickerOptions = {
   minDate: this.getMinDate(),
   maxDate: this.getMaxDate()
 };

Global Configuration:

const configDatepicker = (uibDatepickerConfig, uibDatepickerPopupConfig) => {
    'ngInject';
    uibDatepickerConfig.showWeeks = false;
    uibDatepickerPopupConfig.datepickerPopup = 'dd/MM/yyyy';
    uibDatepickerPopupConfig.currentText = 'Hoje';
    uibDatepickerPopupConfig.clearText = 'Limpar';
    uibDatepickerPopupConfig.closeText = 'Fechar';
};

Current Component:

Desired Component (with the button inside the calendar):

@typescript-eslint/recommended-type-checked does not find incorrect function argument type

I have a function in my code that I am calling with the incorrect argument type; I have integrated with ESLint (v8.57.1) and installed the TypeScript plugin. When I run it, it skips through the error I am trying to catch.

function test(a: string, b: number) {
...
}

// Compiler errors out, but the linter doesn't.
test(true);

That said, I can catch the error via npx tsc -noemit, following the answer here, ESLint not reporting TypeScript compiler type checking errors.

The answer seems odd since based on the recent documentation, TypeScript ESLint should catch these types of error, see https://typescript-eslint.io/getting-started/typed-linting.

// https://docs.expo.dev/guides/using-eslint/
module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2021,
    sourceType: 'module',
    project: './tsconfig.json',
  },
  ignorePatterns: ['/dist/*'],
  extends: [
    'expo',
    'plugin:react/recommended',
    'plugin:prettier/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-type-checked',
  ],
  plugins: ['@typescript-eslint', 'prettier'],
  rules: {
    'prettier/prettier': 'error',
    'react/react-in-jsx-scope': 'off',
    'react/prop-types': 'off',
    '@typescript-eslint/no-require-imports': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
  overrides: [
    {
      files: ['*.js'],
      extends: ['plugin:@typescript-eslint/disable-type-checked'],
    },
  ],
};

HTML OverlayScrollbars – onScroll event is not called

I’m trying to implement OverlayScrollbars see url https://kingsora.github.io/OverlayScrollbars/ in HTML but I have a problem with the onScroll callbacks. I don’t know why but the onScroll event is not being called.

here is my code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>OverlayScrollbars</title>

    <!-- overlayscrollbars css -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/overlayscrollbars/2.10.1/styles/overlayscrollbars.css"
        rel="stylesheet" />

    <style>
        /* Basic styles for the scrollable container */
        .scroll-container {
            max-height: 300px;
            overflow: auto;
            border: 1px solid #ccc;
            background-color: blueviolet;
            padding: 10px;
        }
    </style>

    <!-- overlayscrollbars js -->
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/overlayscrollbars/2.10.1/browser/overlayscrollbars.browser.es6.js"
        defer></script>

</head>

<body>

    <div id="target" class="scroll-container">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante
            dapibus diam.</p>
        <p>Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris.</p>
        <p>Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla.</p>
        p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante
        dapibus diam.</p>
        <p>Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris.</p>
        <p>Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla.</p>
        p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante
        dapibus diam.</p>
        <p>Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris.</p>
        <p>Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla.</p>
        p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante
        dapibus diam.</p>
        <p>Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris.</p>
        <p>Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla.</p>
        p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante
        dapibus diam.</p>
        <p>Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris.</p>
        <p>Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla.</p>
    </div>

    <!-- overlayscrollbars initialization -->
    <script defer>

        // Save the OverlayScrollbars instance

        const overlayScrollInit = () => {
            try {
                osInstance = OverlayScrollbarsGlobal.OverlayScrollbars(document.getElementById('target'), {
                    scrollbars: {
                        autoHide: "move",
                        autoHideDelay: 300,
                    },
                    callbacks: {
                        onScroll: (e) => {
                            console.log("Scroll event:", e);
                        }
                    }
                });
                console.log("OverlayScrollbars initialized successfully:", osInstance);
            } catch (error) {
                console.error("OverlayScrollbars initialization failed:", error);
            }
        };

        window.addEventListener("DOMContentLoaded", overlayScrollInit);

        // Check after loading the DOM (in case initialization fails)
        window.addEventListener("load", () => {
            if (!osInstance) {
                console.error("OverlayScrollbars initialization failed (after DOMContentLoaded and load)!");
            }
        });

        // Function for destroying the instance (e.g. when dynamically changing the content)
        function destroyOverlayScrollbars() {
            if (osInstance) {
                osInstance.destroy();
                osInstance = null;
                console.log("OverlayScrollbars destroyed.");
            }
        }

    </script>
</body>

</html>

Thanks a lot. I would be happy for any advice.
” “

Getting max of multiple columns added together in Sequelize

This is what I’m trying to replicate with Sequelize: SELECT MAX(col1 + col2 + col3) FROM table WHERE col4 = x

I’m aware of the following ways to find a max value:

let result = await Model.max('col1', {
            where: {
                col4: x
            }
        });
let result = await Model.findOne({
            attributes: [
                [sequelize.fn('MAX', sequelize.col('col1')), 'col1max']
            ],
            where: {
                col4: x
            }
        });

This only allows me to get the max of a single column, however. Is there a quick way to modify one of these queries to get the value I need or do I need to just get all the rows and calculate it myself?

How to get unique values from an array of objects in a Map?

I have a Map in the following format.

const a = [{ data: ['name1', true, true] }, { data: ['name2', false, true] }];
const b = [{ data: ['name3', true, true] }, { data: ['name2', false, true] }];
const c = [];

const map = new Map();
map.set('a', a);
map.set('b', b);
map.set('c', c);

const expectedData = [
  ['name1', true, true],
  ['name2', false, true],
  ['name3', true, true],
]; // remove duplicates and empty arrays. name2 is included only once in the final array

I tried using the spread operator and creating a new set of elements. But the final array includes all the occurrences of ‘name2’ such as: [[‘name1’, true, true], [‘name2’, false, true], [‘name2’, false, true], [‘name3’, true, true]].

Is there an easy way to filter the map’s values based on the first element of the array?

Using asynchronous tasks and batch updates at the same time

I have a react native app connected to Firestore. I also use Cloud Functions to send notifications to each users. The following code works but I recently encountered timeout errors (even with 540 seconds timeout and 512MB memory) :

async function sendNotifications() {
    console.log("Sending notifications for recommended events...");

    // Fetch all events once
    const eventsRef = admin.firestore().collection("Events");
    const eventsSnapshot = await eventsRef
        .where('Start', '>=', new Date())
        .get();

    if (eventsSnapshot.empty) {
        console.log("No upcoming events found.");
        return;
    }
    const allEvents = eventsSnapshot.docs.map(doc => ({ ...doc.data(), docId: doc.id }));

    // Fetch all users
    const usersRef = admin.firestore().collection("Users");
    const usersSnapshot = await usersRef.get();

    let reset = false;

    for (const userDoc of usersSnapshot.docs) {
        try {
            const userData = userDoc.data();
            const { fcmToken, preferences, language = "en", sentNotifications = [] } = userData;

            if (!fcmToken) continue; // Skip users without FCM token
            const userPreferredTags = preferences ? preferences : [];
            let eventToSend = findEventForUser(allEvents, userPreferredTags, sentNotifications);

            // Fallback logic: No matching events, or user has no preferences
            if (!eventToSend) {
                eventToSend = findBangerEvent(allEvents, sentNotifications);
            }
            if (!eventToSend && sentNotifications.length > 0) {
                console.log(`No new events to suggest, resetting`);
                eventToSend = sentNotifications[sentNotifications.length - 1];
                reset = true;
            }

            if (!eventToSend) {
                console.log(`No events to send for user ${userDoc.id}. Skipping.`);
                continue;
            }

            const notificationPayload = createNotificationPayload(
                eventToSend,
                fcmToken,
                language
            );
            await admin.messaging().send(notificationPayload);
            console.log(`Successfully sent message to user ${userDoc.id}, ${notificationPayload.notification.title}`);

            const updatedNotifications = updateSentNotifications(eventToSend, reset ? [] : sentNotifications);
            await userDoc.ref.update({ sentNotifications: updatedNotifications });

        } catch (error) {
            console.error(`Error processing user ${userDoc.id}:`, error);
        }
    }

    console.log("Notifications sent successfully.");
}

I thus moved to asynchronous functions to be able to process users simultaneously but, if I understood correctly, it is also good practice to batch the userDoc updates to Firestore and the FCM messages with sendEach().

So I tried that on the Firebase Emulator using the following code :

async function sendNotifications() {
    console.log("Sending notifications for recommended events...");

    // Fetch all events once
    const eventsRef = admin.firestore().collection("Events");
    const eventsSnapshot = await eventsRef
        .where('Start', '>=', new Date())
        .get();

    if (eventsSnapshot.empty) {
        console.log("No upcoming events found.");
        return;
    }
    const allEvents = eventsSnapshot.docs.map(doc => ({ ...doc.data(), docId: doc.id }));

    // Fetch all users
    const usersRef = admin.firestore().collection("Users");
    const usersSnapshot = await usersRef.get();

    const usersToProcess = usersSnapshot.docs.filter(userDoc => {
        const userData = userDoc.data();
        return true; // Include all users with an FCM token (set to true in emulator)
    });

    console.log(`Processing ${usersToProcess.length} users...`);

    const notifications = [];
    let batch = admin.firestore().batch();
    let batchUserCount = 0; // Track the number of users in the current batch

    const userPromises = usersToProcess.map(async (userDoc) => {
        const userData = userDoc.data();
        const { fcmToken, preferences, language = "en", sentNotifications = [] } = userData;

        const userPreferredTags = preferences || [];
        let eventToSend = findEventForUser(allEvents, userPreferredTags, sentNotifications);

        // Fallback logic: No matching events
        if (!eventToSend) {
            eventToSend = findBangerEvent(allEvents, sentNotifications) ||
                sentNotifications[sentNotifications.length - 1];
        }

        if (!eventToSend) {
            console.log(`No events to send for user ${userDoc.id}. Skipping.`);
            return;
        }

        const notificationPayload = createNotificationPayload(eventToSend, fcmToken ? fcmToken : "ezeazea", language);
        notifications.push(notificationPayload);

        const updatedNotifications = updateSentNotifications(eventToSend, sentNotifications);
        const dataSize = JSON.stringify({ sentNotifications: updatedNotifications }).length;
        console.log(`Estimated size of update: ${dataSize} bytes`);

        batch.update(userDoc.ref, { sentNotifications: updatedNotifications });
        batchUserCount++;

        // If the batch has 100 operations, commit the batch and start a new one
        if (batchUserCount === 100) {
            console.log("Committing Firestore batch...");
            await batch.commit(); // Commit the batch
            batch = admin.firestore().batch(); // Create a new batch
            batchUserCount = 0; // Reset the batch user count
        }
    });

    await Promise.all(userPromises);

    // Commit remaining updates if any users were left in the batch
    if (batchUserCount > 0) {
        console.log("Committing remaining Firestore batch...");
        await batch.commit();
    }

    // Send notifications in bulk (in batches of 100)
    console.log("Sending notifications in bulk...");
    while (notifications.length) {
        const batchNotifications = notifications.splice(0, 100); // Firebase max batch size for FCM
        try {
            await admin.messaging().sendEach(batchNotifications);
        } catch (error) {
            console.error("Error sending notifications:", error);
            // Handle the error as necessary
        }
    }

    console.log("Notifications sent successfully.");
}

But it seems that the asynchronous processing of the users clashes with the batching as I get the following error on the second commit call:

⚠ functions: Error: Cannot modify a WriteBatch that has been committed.

TypeScript: inferring error type from rejected awaited promise?

I have API methods (login is one example below) that deliver their responses using the fetch API through promises, like so:

export const handleResponse = async (response: Response, session?: Session): Promise<Response> => {
    // check for error response
    if (!response.ok) {
        if ([401, 403].includes(response.status) && session?.auth) {
            session?.logout();
        }
        return Promise.reject(response);
    }
    return response;
}

export const login = async (username: string, password: string) => {
    const response = await fetch("/auth/login", {
        method: "POST",
        body: JSON.stringify({ username, password })
    });

    return (await handleResponse(response));
}

I am calling these methods using await syntax:

try {
    const response = await API.client.login(username, password);
    console.log(await response.json());
    // handle response
} catch (error) {
    console.log(await error.json());
    // handle error
}

However, TypeScript does not recognize the type of the error parameter, leading to it to be typed as unknown. This requires me to use some kind of type assertion in order to access properties (like the .json() method), which is clunky.

How can this be resolved?

How to add a suffix to duplicates array of objects using javascript?

I’ve got a following array of objects

let views = [
  {
    name: "A View",
    active: true,
  },
  {
    name: "B View",
    active: false,
  },
  {
    name: "C View",
    active: false,
  }
];

When another elements are added, one by one with the existing name, for example another “A View”, and another “A View” like for example

{
  name: "A View",
  active: true,
}

I want to add the suffix number to the name in the counting order, so I’ve got

[
  {
    name: "A View",
    active: true,
  },
  {
    name: "B View",
    active: false,
  },
  {
    name: "C View",
    active: false,
  },
  {
    name: "A View 2",
    active: true,
  }
]

after the first new “A View” added

And

[
  {
    name: "A View",
    active: true,
  },
  {
    name: "B View",
    active: false,
  },
  {
    name: "C View",
    active: false,
  },
  {
    name: "A View 2",
    active: true,
  },
  {
    name: "A View 3",
    active: true,
  }
];

after the second “A View” element added, and so on…
Is I then remove “A View 2” I want the “2” suffix to be available to add for the new “A view” if I add it. So the next “A View” item will be “A View 2”, not “A View 4”

This is my current solution

const addItem = (item) => {
  views = [...views, item];
  let names = {};

  views.forEach((obj) => {
    if (names[obj.name]) {
      obj.name += " " + ++names[obj.name];
    } else {
      names[obj.name] = 1;
    }
  });

  console.log("views", views);
};

The problem is that the suffix is not adding correctly.
If I call the function 3 times passing the same object, like for example

addItem({
  name: "A View",
  active: true,
});

I will have this

enter image description here

Here is the working example – https://codesandbox.io/p/sandbox/8dhpl3

How to make the connector lines in highcharts look horizontally straight instead of going in different directions?

I am creating a pie chart using Highcharts, but I have an issue with the connector lines. They are currently going in different directions(angled), and I would like them to be straight horizontal, as shown in the attached example. Not sure if its possible?enter image description here

        Highcharts.chart('chart1', {
            chart: {
                type: 'pie',
                backgroundColor: null
            },
            title: {
                text: '',
                align: 'left',
                verticalAlign: 'middle',
                style: {
                    fontSize: '20px',
                    fontWeight: 'bold',
                    color: '#333333'
                }
            },
            plotOptions: {
                pie: {
                    innerSize: '50%',
                    startAngle: 0,
                    endAngle: 180,
                    
                    dataLabels: {
                        enabled: true,
                        connectorShape: 'crookedLine',
                        crookDistance: '70%',
                        format: '{point.name}',
                        style: {
                            fontSize: '14px',
                            color: '#333333'
                        },
                        distance: 60
                    }
                }
            },
            series: [{
                name: 'My Test',
                data: [
                    { name: 'ABCD', y: 25, color: '#6BAED6' },
                    { name: 'XYZM', y: 25, color: '#4292C6' },
                    { name: 'Active bLAM/TEST', y: 25, color: '#2171B5' },
                    { name: 'Sort', y: 25, color: '#112e51' }
                ]
            }]
        });
   
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="chart1" style=" width: 720px; height: 600px; margin: 0 auto;"></div>

enter image description here

Stripe integration results in Network porblem and cors issues

Iv been tryiing to get this api integration to work, when i use postman to try the http://localhost:5001/api/stripe/create-checkout-session POST i get 200k and a session ID in return as well as using curl. When i try the actual redirect on my billing page when cliclking activate subscription nothing happens and console produces a network error:

    Billing-7ca61e132a5214f3.js:1 Error creating checkout session: 
    V
    code
    : 
    "ERR_NETWORK"
    config
    : 
    {transitional: {…}, adapter: Array(3), transformRequest: Array(1),        
    transformResponse: Array(1), timeout: 0, …}
    message
    : 
    "Network Error"
    name
    : 
    "AxiosError"
    request
    : 
    XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0,    
    withCredentials: false, upload: XMLHttpRequestUpload, …}
    stack
    : 
    "AxiosError: Network Errorn    at m.onerror    
    (http://localhost:3001/_next/static/chunks/988-fcb0a835e46419aa.js:1:39051)n       
    at ts.request (http://localhost:3001/_next/static/chunks/988-
    fcb0a835e46419aa.js:1:46641)n    at async i 
    (http://localhost:3001/_next/static/chunks/pages/billing/Billing-  
    7ca61e132a5214f3.js:1:1042)"
    [[Prototype]]
    : 
    Error
    i   @   Billing-7ca61e132a5214f3.js:1

and issue: Ensure CORS response header values are valid
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request.

To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values.

Note that if an opaque response is sufficient, the request’s mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque).

1 request
Request Status Preflight Request (if problematic) Header Problem Invalid Value (if available)

create-checkout-session blocked
create-checkout-session Access-Control-Allow-Origin Missing Header
Learn more: Cross-Origin Resource Sharing (CORS)

iv tried multiple things and cannot get this to work. Any help or insight would be great.

my server index.js

    const express = require("express");
    const cors = require("cors");
    require("dotenv").config();

    const app = express();
    const PORT = process.env.PORT || 5001;

    // Middleware
    app.use(cors());
    app.use(express.json());

   // Import routes
   const stripeRoutes = require("./routes/stripe");
   app.use("/api/stripe", stripeRoutes);

   // Test route
   app.get('/api/test', (req, res) => {
   res.send('API is working!');
   });

   // Start server
   app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));

my front end billing.js

    import React from "react";
    import { loadStripe } from "@stripe/stripe-js";
    import { Elements } from "@stripe/react-stripe-js";
    import { useUser } from '../../context/UserContext';
    import axios from 'axios';
    
    const stripePromise = loadStripe("your-publishable-key");
    
    const Billing = () => {
    const userContext = useUser();
    const subscriptionStatus = userContext?.subscriptionStatus;
    const setSubscriptionStatus = userContext?.setSubscriptionStatus;
    
    const handleSubscriptionChange = async (priceId) => {
    try {
      console.log('Creating checkout session...');
      const response = await axios.post('http://localhost:5001/api/stripe/create-   
    checkout-session', {
        name: "Basic Plan",
        price: 1000,
        successUrl: "http://localhost:3001/success",
        cancelUrl: "http://localhost:3001/cancel"
      }, {
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const { id } = response.data;
      console.log('Checkout session created:', id);
      const stripe = await stripePromise;
      const { error } = await stripe.redirectToCheckout({ sessionId: id });
      if (error) {
        console.error('Error redirecting to checkout:', error);
      }
    } catch (error) {
      console.error('Error creating checkout session:', error);
      console.error('Error details:', error.response ? error.response.data :     
    error.message);
    }
    };
    
    return (
    <Elements stripe={stripePromise}>
      <div>
        <h1>Billing</h1>
        <p>Manage your billing information here.</p>
        <p>Current subscription status: {subscriptionStatus}</p>
        <button onClick={() =>   
     handleSubscriptionChange('price_1Hh1Y2I4s2eZvKYlo2L8U7c2')}>Activate 
     Subscription</button>
        <button onClick={() => 
     handleSubscriptionChange('price_1Hh1Y2I4s2eZvKYlo2L8U7c3')}>Deactivate    
     Subscription</button>
      </div>
    </Elements>
    );
    };
    
    export default Billing;
    stripe.js: 
`
    const express = require('express');
    const router = express.Router();
    const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

    router.post('/create-checkout-session', async (req, res) => {
    const { name, price, successUrl, cancelUrl } = req.body;

    console.log('Received request to create checkout session');
    console.log('Request body:', req.body);

    try {
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ['card'],
      line_items: [
        {
          price_data: {
            currency: 'usd',
            product_data: {
              name: name,
            },
            unit_amount: price,
          },
          quantity: 1,
        },
      ],
      mode: 'payment',
      success_url: successUrl,
      cancel_url: cancelUrl,
     });

    console.log('Checkout session created:', session.id);
    res.json({ id: session.id });
   } catch (error) {
    console.error('Error creating checkout session:', error);
    res.status(500).json({ error: error.message });
   }
   });

   module.exports = router;
`

i tried changing cords header, making sure the api url is correct, relaunching the server i stil get the samer result

How to parse DOM elements with Flowbite’s library

I’m working on a website that is a CRUD. Since it’s hosted on a managed server, I’m using HTML, Tailwind CSS, Flowbite CSS/JS, vainilla JS and jQuery for the front end. The interface has two modals that work with the Flowbite library and have the following ID’s: modal-customer and modal-edit. Both of these are in my main HTML file when the DOM is loaded so Flowbite can initialize the modals without issues.

First, the modal-customer is opened with the following button that have the data-target-* and data-toggle-* attributes as stated in the official documentation. Then, the modal-customer has a table that is dynamically populated with records received from the back end. This data is received through AJAX and then used to append rows to the table. The last column has a edit button that also has the data-target-* and data-toggle-* attributes. However, since these elements weren’t present when the DOM loaded and Flowbite parsed it, they don’t work to open the second modal-edit window.

I tried to re initialize Flowbite using window.initFlowbite(). While this does make the edit buttons work, it re initializes everything, causing the modal-customer window to open twice: once for the instance that was originally opened through the UI and once for the line window.initFlowbite().

I also tried to handle the events generating by clicking the edit buttons instead:

if (event.target && event.target.closest('.service_edit')) {
   const modal = FlowbiteInstances.getInstance('Modal', 'modal-edit');
   modal.show();
}

While this does work, Flowbite fails to identify that buttons exist to open the modal-edit. This causes the following message to constantly display in the console:

Modal with id modal-edit has not been initialized. Please initialize it using the data-modal-target attribute.

I’d appreciate any help to solve this. I thought of using the second approach, handling clicks to the edit buttons manually, and adding a hidden element to the HTML file with the data-target-* and data-toggle-* attributes linked to the modal-edit so Flowbite reads that and doesn’t display the console message. However, this feels like an inappropriate solution. Is there any way to parse given DOM elements with Flowbite instead of parsing everything again with window.initFlowbite()?