When adding an item to the cart, in 10% of cases, my item is undefined [closed]

I’m doing a project using Vite and JS. I have a homepage component where I have code to add a product to the cart. This code works, but in 10% of cases, in the Chrome console, my product is undefined and not added to the cart. What could be the problem? Thanks!

Chrome console

export class HomePage extends Component {
  constructor() {
    super();
    this.template = template();
    this.state = {
      
      orderCart: [],
    };
  }

  addToCard = (e) => {
    if (e.target.closest(".add-to-cart")) {
      let price = e.target.parentElement.parentElement.dataset.price;
      let name = e.target.parentElement.parentElement.parentElement.dataset.name;
      let img = e.target.parentElement.parentElement.parentElement.dataset.img;
      
      const cartItems = { price, name, img };
      apiService.post("/order", cartItems).then(() => {
        this.setState({
          ...this.state,
          orderCart: this.state.orderCart?.concat(cartItems),
        });
        console.log(cartItems);
      })
    }
  };

  componentDidMount() {
    this.addEventListener("click", this.addToCard);
    
  }

  componentWillUnmount() {
    this.removeEventListener("click", this.addToCard);
  }
}

customElements.define('home-page', HomePage);

For network query i use Axios Api.
For data storage I use Firebase(Realtime Database and Storage).
Product(I’m using Handlebars for HTML):

{{#each products}}
          <div class="w-full md:w-1/3 xl:w-1/4 p-6 flex flex-col" data-id="{{this.id}}">
            
            <div
              data-img="{{this.img}}"
              data-name="{{this.name}}"
              
            >
              <img class="hover:grow hover:shadow-lg" src="{{this.img}}" alt="product" />
              <p data-name="{{this.name}}">{{this.name}}</p>
              <div data-price="{{this.price}}" class="pt-3 flex items-center justify-between">
                <p data-price="{{this.price}}" class="pt-1 text-gray-900">{{this.price}}</p>

                <button class="add-to-cart">
                 <svg class="h-6 w-6 fill-current text-gray-500 hover:text-black" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                   <path d="M12,4.595c-1.104-1.006-2.512-1.558-3.996-1.558c-1.578,0-3.072,0.623-4.213,1.758c-2.353,2.363-2.352,6.059,0.002,8.412 l7.332,7.332c0.17,0.299,0.498,0.492,0.875,0.492c0.322,0,0.609-0.163,0.792-0.409l7.415-7.415 c2.354-2.354,2.354-6.049-0.002-8.416c-1.137-1.131-2.631-1.754-4.209-1.754C14.513,3.037,13.104,3.589,12,4.595z M18.791,6.205 c1.563,1.571,1.564,4.025,0.002,5.588L12,18.586l-6.793-6.793C3.645,10.23,3.646,7.776,5.205,6.209 c0.76-0.756,1.754-1.172,2.799-1.172s2.035,0.416,2.789,1.17l0.5,0.5c0.391,0.391,1.023,0.391,1.414,0l0.5-0.5 C14.719,4.698,17.281,4.702,18.791,6.205z" />
                 </svg>
                </button>
              </div>
            </div>
          </div>
        {{/each}}

I thought the problem might be with the add to cart button. I tried it by id, but the product was still undefined after several attempts.

How to add HTML legend to simple line graph?

How would I add an HTML legend to this very simple line graph? The documentation is not very straight forward about this…

import React from "react";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Line } from "react-chartjs-2";
import faker from "faker";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
);

export const options = {
  responsive: true,
  plugins: {
    htmlLegend: {
      containerID: "legend-container",
    },
    legend: {
      display: false,
    },
    title: {
      display: true,
      text: "HTML Legend",
    },
  },
};

const labels = ["January", "February", "March", "April", "May", "June", "July"];

export const data = {
  labels,
  datasets: [
    {
      label: "Dataset 1",
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: "rgb(255, 99, 132)",
      backgroundColor: "rgba(255, 99, 132, 0.5)",
    },
    {
      label: "Dataset 2",
      data: labels.map(() => faker.datatype.number({ min: -1000, max: 1000 })),
      borderColor: "rgb(53, 162, 235)",
      backgroundColor: "rgba(53, 162, 235, 0.5)",
    },
  ],
};

export function App() {
  return (
    <div>
      <Line options={options} data={data} />
      <div id="legend-container" />
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-chartjs-2/5.3.0/index.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="module" defer src="./index.tsx"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

React Native Webview Pull to refresh is not working on android

In my React Native app, I’m using react-native-webview to display web content. I’d like to add a pull-to-refresh feature to the WebView. I’ve set:

<WebView
  source={{ uri: 'https://example.com' }}
  pullToRefreshEnabled={true}
/>

but it only works on iOS. According to the documentation, pullToRefreshEnabled is iOS‑only. Does Android have an equivalent? I also tried wrapping the WebView in a ScrollView with a RefreshControl, but sometimes the native scroll view takes over and sometimes the WebView does, causing pull-to-refresh to trigger even when I’m not at the top. How can I implement pull-to-refresh on Android with react-native-webview?

Here is complete webview component

import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';
import { StyleSheet } from 'react-native';
import { BASE_URL } from '../constants/global.constants';
import { injectedJavaScript } from '../utils/injectJavascript';
import { handleWebViewMessage } from '../utils/messageHandler';
import { shouldStartLoadWithRequest } from '../utils/navigationHandler';
import { webViewConfig } from '../config/webviewConfig';

const Webview = () => {
  const webviewRef = useRef<WebView>(null);

  const handleHttpError = (error: any) => {
    console.log('WebView HTTP error:', error);
  };

  return (
    <WebView
      ref={webviewRef}
      source={{ uri: BASE_URL }}
      style={styles.webview}
      onHttpError={handleHttpError}
      domStorageEnabled={true}
      injectedJavaScript={injectedJavaScript}
      pullToRefreshEnabled={true}
      onMessage={handleWebViewMessage}
      onShouldStartLoadWithRequest={request =>
        shouldStartLoadWithRequest(request, webviewRef)
      }
      {...webViewConfig}
      mixedContentMode="always"
    />
  );
};

export default Webview;

const styles = StyleSheet.create({
  webview: {
    flex: 1,
  },
});

Chrome DevTools – Memory Tab

After getting a snapshot I see something like this:
enter image description here

While I was able to identify the first entry, I can’t do it with the second entry. Any idea how to find the actual name of that object used in the code? Interesting that both entries have a similar content.

Efficient way to partially match stringified JSON in a string column using Prisma (without full JSON match)

I’m trying to find a record where a column (payload) stores a stringified JSON object. The column type is string (as defined in Prisma schema) — so it’s not a JSON or JSONB type.

I want to check if a subset of the JSON content exists in the string, without matching the entire object.

Here’s a sample value stored in the payload column:

{
  "triggerEvent": "RESERVATION_EXPIRED",
  "id": 16,
  "eventTypeId": 3,
  "userId": 4,
  "slotUtcStartDate": "2025-07-25T03:30:00.000Z",
  "slotUtcEndDate": "2025-07-25T04:00:00.000Z",
  "uid": "014cbb69-fa4b-421b-8c6d-af0ac7f4184e",
  "releaseAt": "2025-07-24T20:56:33.000Z",
  "isSeat": false
}

I’m only interested in this part of the object:

"eventTypeId": 3,
"userId": 4,
"slotUtcStartDate": "2025-07-25T03:30:00.000Z",
"slotUtcEndDate": "2025-07-25T04:00:00.000Z",
"uid": "014cbb69-fa4b-421b-8c6d-af0ac7f4184e"

Here’s my current Prisma-based query:

const { id, releaseAt, isSeat, ...rest } = slot;
const restString = JSON.stringify(rest);
const searchString = restString.slice(1, -1); // remove outer {}

const isWebhookScheduledTriggerExists = await prisma.webhookScheduledTriggers.findFirst({
  where: {
    payload: {
      contains: searchString,
    },
  },
});

The Problem:

I was told this approach is inefficient and not production-safe.

Constraint:

I cannot convert the column to JSON/JSONB or change its type — it must remain a string.

My Question:

Is there a more efficient or reliable way to match a partial stringified JSON object in a string column using Prisma or raw SQL?

Code fullscreen element responsive by clicking fullscreen button? Simulate a mouse click?

I’m trying to get fullscreen for iframe element immediately responsive to user input (e.g., keyboard input) without having to manually click when fullscreen to get the fullscreen responsive (think of it as a youtube video or a browser game where fullscreening the iframe element will not cut off user input, they don’t have to click the fullscreen just to resume playing iframe)

Here I still can’t get fullscreened iframe to still be responsive to user inputs without clicking on fullscreen. How do I simulate a click whenever fullscreen element is clicked on, so that fullscreen is responsive immediately without user clicking?

let elem = document.getElementById("gamescreen");

function fullscreen() {
  if (elem.requestFullscreen) {
    elem.requestFullscreen();
  } else if (elem.webkitRequestFullscreen) {
    /* Safari */
    elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) {
    /* IE11 */
    elem.msRequestFullscreen();
  }
}

let fse = document.getElementById("fullscreen");
fse.onclick = fullscreen;
fse.click()
document.onclick = fullscreen;
<div class="gamescreen">
  <iframe width="100%" height="100%"  controls id="gamescreen" frameborder="0" src=""></iframe>
</div>

<div id="fullscreen" title="Fullscreen" onclick="fullscreen();">
  <img src="https://i.postimg.cc/0ykypt59/gameplayerfullscreen.png" style="width:22px;height:20px;">
</div>

Why does my async function return a pending Promise instead of the expected value in JavaScript?

I’m trying to call an async function and get the result, but instead of the actual data, I get a pending Promise. Here’s a simplified version of my code:

async function getData() {
  const response = await fetch('https://api.example.com/data');
  const result = await response.json();
  return result;
}

const data = getData();
console.log(data); // This logs: Promise { <pending> }

How can I get the actual result instead of a pending Promise? I understand async functions return Promises, but what’s the correct way to handle this so I can use the data?

Issue with mousedown event getting stuck

I’m building an Etch-a-Sketch per The Odin Project’s curriculum.

On page load, makeGrid() creates a default 10×10 grid of divs (adjustable between 2×2 and 64×64). Then draw() is called—both on load and whenever the grid size changes—to enable drawing by clicking and dragging across the grid.

Drawing works using mousedown, mouseup, and mouseover events to track whether the mouse is held down. I use an isMouseDown flag for this.

The problem: when I click and quickly drag, sometimes the mouseup event doesn’t fire, and the mouse stays “stuck” in drawing mode. It continues coloring tiles even after releasing the button. Slower dragging usually works fine.

I initially used just mousedown and mouseover, but added mouseup and the isMouseDown flag to improve accuracy. Still, the issue persists.

There are no errors in the console. Here’s the CodePen link with all the code if you’d like to test it.

https://codepen.io/kevyozev-the-sasster/pen/PwPNGwE

function makeGrid() {
  let number = input.value;
  if (number < 0 || number > 64 || isNaN(number)) {
    promptText.textContent = `Invalid number. Generating 10 x 10 grid. Please enter a number between 2 and 64.`;
  } else {
    promptText.textContent = "";
    input.value = "";
    canvas.innerHTML = "";
  }
  if (number == 0 || number > 64 || number == "") {
    canvas.innerHTML = "";
    for (let i = 0; i < 10; i++) {
      const row = document.createElement("div");
      row.classList.add("rows");
      canvas.appendChild(row);

      for (let j = 0; j < 10; j++) {
        const column = document.createElement("div");
        column.classList.add("columns");
        row.appendChild(column);
      }
    }
  } else {
    promptText.textContent = `Generating a ${number} x ${number} grid...`;
    for (let i = 0; i < number; i++) {
      const row = document.createElement("div");
      row.classList.add("rows");
      canvas.appendChild(row);

      for (let j = 0; j < number; j++) {
        const column = document.createElement("div");
        column.classList.add("columns");
        row.appendChild(column);
      }
    }
    draw();
  }
}


let isMouseDown = false;

document.addEventListener("mousedown", () => {
  isMouseDown = true
});
document.addEventListener("mouseup", () => {
  isMouseDown = false
});



function draw() {
  let columns = document.getElementsByClassName("columns");
  for (let i = 0; i < columns.length; i++) {
    columns[i].addEventListener("mousedown", changeColors);
    columns[i].addEventListener("mouseover", function() {
      if (isMouseDown) {
        changeColors.call(this);
      }
    })
  }
}
<div id="container">
  <div id="canvas"></div>
</div>

Header alignment with sort/filter icons in PrimeReact DataTable

I have a PrimeReact DataTable with multiple columns.
Each column has a text header, optionally with sort and filter options.
Alignment of the columns can differ, and I would like the alignment of the headers to match that of the columns. But if the sort and/or filter options are active for that column, I want the sort and filter icons to ALWAYS be right aligned, regardless of the text alignment of that column header.

I can use the alignHeader property of the Column to decide if I want the header text to be aligned left, right of center. But that will make the sort and filter icons left or center aligned as well.

For a right aligned header it’s obvious, as using alignHeader will ensure that both the header text and the icons are right aligned

And if all column headers should be left aligned, I know I could use

            display: flex;
            justify-content: space-between;

to solve this, as it will move the header text to the left and the icons to the right (regardless of the alignHeader values).
But that doesn’t work when I want to have different alignment in the different column headers.

And I can’t figure out how to properly solve it for center aligned header text at all.

So what would be the best/easiest way to handle this?

With the exception of the above mentioned left alignment solution, every solution I tried resulted in the header text and the header icons being grouped together and both being aligned the same, which is not what I want.

mediainfo.js 0.3.5 giving error loading MediaInfoModule.wasm

I have an AWS javascript lambda using CommonJS modules running under Node.js 22.x. I’m running currently with mediainfo.js 0.1.9 and everything works fine. I tried to upgrade to mediainfo.js 0.3.5 and, after making appropriate adjustments (like changing new MediaInfoFactory(..) to mediaInfoFactory(..)), I get the following errors when I’m trying to run:

2025-07-25T05:29:49.977Z    da5eb22d-0494-41dd-8aa8-194b0e8b42be    ERROR   failed to asynchronously prepare wasm: CompileError: WebAssembly.instantiate(): invalid value type 0x64 @+249
2025-07-25T05:29:49.977Z    da5eb22d-0494-41dd-8aa8-194b0e8b42be    ERROR   Aborted(CompileError: WebAssembly.instantiate(): invalid value type 0x64 @+249)
2025-07-25T05:29:49.977Z    da5eb22d-0494-41dd-8aa8-194b0e8b42be    ERROR   RuntimeError: Aborted(CompileError: WebAssembly.instantiate(): invalid value type 0x64 @+249). Build with -sASSERTIONS for more info.
    at abort (/var/task/node_modules/mediainfo.js/dist/cjs/MediaInfoModule.cjs:297:15)
    at instantiateArrayBuffer (/var/task/node_modules/mediainfo.js/dist/cjs/MediaInfoModule.cjs:343:9)
    at async createWasm (/var/task/node_modules/mediainfo.js/dist/cjs/MediaInfoModule.cjs:417:22)
    at async /var/task/node_modules/mediainfo.js/dist/cjs/MediaInfoModule.cjs:2645:23

I temporarily built a custom locateFile function and passed it to the 0.3.5 mediaInfoFactory and I verified that I’m loading MediaInfoModule.wasm from the correct location.

The error is on this statement:
let mi = await mediaInfoFactory({chunkSize: CHUNK_SIZE, coverData: false, format: 'JSON'});

and the require that I’m using is:
const { mediaInfoFactory } = require('mediainfo.js');

I’m not sure what I’m doing wrong or if it’s something with my environment or what.

I appreciate any help. Thanks, Gary

Opening website on localhost show black page

This is the black page shown when I open it on the localhost server.

I have three websites on the localhost XAMPP server. Two of them are on WordPress, which works fine, but when I open the third website, which is a non-WordPress site, it shows a black page. whereas the website from the previous two weeks is working fine. It suddenly began to show a black page. I don’t know what is the reason behind this.

React Mixed Content

I have deployed an API server and a client to azure containers. The client makes HTTPS requests to the API URL, This URL is set both at build time and as env variable, following the REACT_APP_API naming convention.

If I go to the API swagger, all the endpoints works.
But I’m facing a problem on the client side, when for some endpoints it works and makes the https request, but for others it makes an http request, which ends up with the error:

The page at 'https://myapp.westus.azurecontainerapps.io/jobs' was loaded over HTTPS, 
but requested an insecure XMLHttpRequest endpoint 
'http://myapp-api.westus.azurecontainerapps.io/v1/scheduler'. 
This request has been blocked; the content must be served over HTTPS.

The jobs page has a button that makes the call to /scheduler, they both share the same apiClient object, like this:

const apiURL: string = "https://myapp-api.westus.azurecontainerapps.io"; // also tried process.env.REACT_APP_API;

const apiClient = axios.create({
    baseURL: `${apiURL}/v1`,
    headers: {
        'Content-Type': 'application/json',
    },
});

I’m 100% sure this apiClient is the only one used in all the app, and no hardcoded htpp request is made. I hardcoded for now the HTTPS URL for testing purposes.

For example, in this endpoint it works as expected (and other endpoints as well, post, get, etc):

export async function fetchDatasets(datasetId=null) {
    try {
        const endpoint = datasetId ? `/datasets/${encodeURIComponent(datasetId)}` : '/datasets';
        const response = await apiClient.get(endpoint);
        return response.data;
    } catch (error) {
        console.error('Error fetching datasets:', error);
        throw error;
    }
}

But here is where I’m having the issue:

export async function createSchedule(data: ScheduleRequest): Promise<any> {
    try {
        const response = await apiClient.post('/scheduler/', data);
        return response.data;
    } catch (error) {
        console.error('Error creating schedule request:', error);
        throw error;
    }
}

And also in this one, when jobId is null, it renders the /jobs page and it works, but when jobId is not null, it renders the /jobs/{jobId} page and it fails:

export async function fetchJobs(jobId = null) {
    try {
        const endpoint = jobId ? `/jobs/${encodeURIComponent(jobId)}` : '/jobs';

        const response = await apiClient.get(endpoint);
        return response.data;
    } catch (error) {
        console.error('Error fetching Jobs:', error);
        throw error;
    }
}

The only difference I can tell, and I’m not sure if it might be the issue, it’s that in the cases that work, the browser url (e.g /datasets) is the same as the API request, but for example, in the scheduling case, it happens that it’s made from the browser page /jobs and requesting /scheduler. But anyways the api and client are deployed to different urls

How exactly am I supposed to use EmailJS on a react Form?

I am currently trying to use Emailjs for the first time on a react form but I am having all kinds of trouble to get things to work accordingly. I have read documentation and tried to implement some of solutions, but nothing seems to work. I am lost in regards to what is wrong with the form.

On Submit, the content of the form does show up on console but I am not receiving the email with contents from the form.

My contact.jsx component is as follows:

import { useState } from "react";
import React, { useRef } from 'react';
import emailjs from "@emailjs/browser";


const initialState = {
  name: "",
  email: "",
  message: "",
};
export const Contact = (props) => {
  const [{ name, email, message }, setState] = useState(initialState);
  const form = useRef();

 const handleChange = (e) => {
  const { name, value } = e.target;
  setState((prevState) => ({ ...prevState, [name]: value }));};

const clearState = () => setState({ ...initialState });


const handleSubmit = (e) => {
e.preventDefault();
console.log(name, email, message);
emailjs
  .sendForm(process.env.SERVICE_ID,  process.env.TEMPLATE_ID, e.target, process.env.PUBLIC_KEY)
  .then(
    (result) => {
      console.log(result.text);
      clearState();
    },
    (error) => {
      console.log(error.text);
    }
  );
 };

 return (
<div>
  <div id="contact">
    <div className="container">
      <div className="col-md-8">
        <div className="row">
          <div className="section-title">
            <h2>Get In Touch</h2>
            <p>
              Please fill out the form below to send us an email and we will
              get back to you as soon as possible.
            </p>
          </div>
          <form name="sentMessage" validate onSubmit={handleSubmit}>
            <div className="row">
              <div className="col-md-6">
                <div className="form-group">
                  <input
                    type="text"
                    id="name"
                    name="name"
                    className="form-control"
                    placeholder="Name"
                    required
                    onChange={handleChange}
                  />
                  <p className="help-block text-danger"></p>
                </div>
              </div>
              <div className="col-md-6">
                <div className="form-group">
                  <input
                    type="email"
                    id="email"
                    name="email"
                    className="form-control"
                    placeholder="Email"
                    required
                    onChange={handleChange}
                  />
                  <p className="help-block text-danger"></p>
                </div>
              </div>
            </div>
            <div className="form-group">
              <textarea
                name="message"
                id="message"
                className="form-control"
                rows="4"
                placeholder="Message"
                required
                onChange={handleChange}
              ></textarea>
              <p className="help-block text-danger"></p>
            </div>
            <div id="success"></div>
            <button type="submit" className="btn btn-custom btn-lg">
              Send Message
            </button>
          </form>
        </div>
      </div>
     </div>
     </div>
     

How to build multiple HTML entry points with TypeScript injection and nested output folders in Vite?

Background

I’m migrating a complex multi-page application from Webpack to Vite. Each HTML file has a corresponding .ts script, and the files live in nested directories.

Note: These entry HTML and TS files do not refer to each other (Webpack automate this injection)

src/
  index.html
  index.ts
  user/login/index.html
  user/login/index.ts
  admin/dashboard.html
  admin/dashboard.ts

Goal:

  • Automatically inject the matching .ts script into each HTML file
  • Preserve the nested folder structure in the final release/ build
  • Output HTML and JS like:
release/
  index.html
  user/login/index.html
  admin/dashboard.html
  scripts/
    index.js
    user/login/index.js
    admin/dashboard.js

What I’ve tried:

I used vite-plugin-html and vite-plugin-html-template-mpa with a list of page definitions. I also defined the input entries using .ts files.

However:

  • The HTML files were either flattened (e.g. dashboard.html instead of admin/dashboard.html)
  • Or they didn’t get emitted at all
  • Script injection was inconsistent or missing

This is my vite.config.js

import { defineConfig } from "vite";
import path from "path";
import htmlTemplateMpa from "vite-plugin-html-template-mpa";

const pages = [
  "index",
  "user/login/index",
  "admin/dashboard"
];

export default defineConfig(() => {
  const entries = pages.reduce((acc, page) => {
    acc[page] = path.resolve(__dirname, `src/${page}.ts`);
    return acc;
  }, {});

  return {
    build: {
      outDir: "release",
      rollupOptions: {
        input: entries,
        output: {
          entryFileNames: "scripts/[name].js",
          chunkFileNames: "scripts/chunks/[name].js",
          assetFileNames: "assets/[name].[ext]"
        }
      }
    },
    plugins: [
      htmlTemplateMpa({
        pages: pages.map((page) => ({
          template: `src/${page}.html`,
          entry: `${page}.ts`,
          filename: `${page}.html`
        })),
        minify: true
      })
    ]
  };
});

Problem

  • The HTML files are not included in the output directory at all.
  • The corresponding .ts files build correctly and show up in release/scripts, but no HTML.
  • If I change the input to use .html, then no JS is injected.

How can I configure Vite to:

  • Use my .html files as templates
  • Inject the matching .ts entry automatically
  • Preserve the nested folder structure in the final build output