Problem sending audio data to Google Speech To Text API with ReactJS

I’m working on a project that does real-time audio analysis. The first chunk sent after pressing the Start button always gives the output “Final Transcription:”, but the subsequent ones give the output “No speech detected in audio”. Also, if I press the stop button and then press start again, the above happens again. I’m using MediaRecorder.jsx to record users voice on another page and it works fine. I tried to fix it with AI but it got more complicated. Please help me.
My code

import { LiveAudioVisualizer } from "react-audio-visualize";
import { useMediaRecorder } from "./MediaRecorder";

const Visualizer = () => {
  const {
    mediaRecorder,
    isRecording,
    startRecording,
    stopRecording,
    recordedChunks,
    resetRecording,
  } = useMediaRecorder();
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [transcription, setTranscription] = useState("");
  const [accumulatedChunks, setAccumulatedChunks] = useState([]);
  const transcriptionRef = useRef("");
  const lastChunkRef = useRef(null);
  const resetIntervalRef = useRef(null);
  const lastSentTimestamp = useRef(Date.now());

  useEffect(() => {
    if (mediaRecorder && mediaRecorder.state === "recording") {
      setIsSpeaking(true);
    } else {
      setIsSpeaking(false);
    }
  }, [mediaRecorder]);

  // Reset recording every 30 seconds
  useEffect(() => {
    if (isRecording) {
      resetIntervalRef.current = setInterval(() => {
        resetRecording();
      }, 30000);
    }

    return () => {
      if (resetIntervalRef.current) {
        clearInterval(resetIntervalRef.current);
      }
    };
  }, [isRecording, resetRecording]);

  // Handle new chunks
  useEffect(() => {
    if (recordedChunks.length > 0) {
      const lastChunk = recordedChunks[recordedChunks.length - 1];

      if (lastChunk !== lastChunkRef.current && lastChunk.size > 0) {
        console.log("New chunk received:", {
          size: lastChunk.size,
          time: new Date().toISOString(),
          totalChunks: accumulatedChunks.length,
        });

        setAccumulatedChunks((prev) => [...prev, lastChunk]);
        lastChunkRef.current = lastChunk;
      }
    }
  }, [recordedChunks]);

  // Handle transcription
  useEffect(() => {
    const sendAudioForTranscription = async () => {
      if (accumulatedChunks.length > 0) {
        const audioBlob = new Blob(accumulatedChunks, {
          type: "audio/webm;codecs=opus",
        });

        if (audioBlob.size === 0) {
          console.log("Empty audio blob, skipping");
          return;
        }

        const currentTimestamp = Date.now();
        if (currentTimestamp - lastSentTimestamp.current < 2000) {
          console.log("Skipping request due to rate limit");
          return;
        }

        lastSentTimestamp.current = currentTimestamp;

        const formData = new FormData();
        formData.append("audio", audioBlob);

        try {
          const response = await fetch("http://localhost:3000/transcribe", {
            method: "POST",
            body: formData,
          });

          const data = await response.json();
          if (data.transcription) {
            transcriptionRef.current += " " + data.transcription;
            setTranscription(transcriptionRef.current.trim());
            setAccumulatedChunks([]); // Clear only after successful transcription
          }
        } catch (error) {
          console.error("Transcription error:", error);
        }
      }
    };

    const transcriptionInterval = setInterval(() => {
      sendAudioForTranscription();
    }, 2000);

    return () => clearInterval(transcriptionInterval);
  }, [accumulatedChunks]);

  return (
    <div className="container mt-5 poppins-regular">
      <div className="row justify-content-center mb-4">
        <div className="col-auto">
          <button
            className="btn btn-primary me-2"
            onClick={startRecording}
            disabled={isRecording}
          >
            Start Recording
          </button>
          <button
            className="btn btn-danger"
            onClick={stopRecording}
            disabled={!isRecording}
          >
            Stop Recording
          </button>
        </div>
      </div>
      {/* Transcription Display */}
      {transcription && (
        <div className="row justify-content-center mb-4">
          <div className="col-auto">
            <div className="card p-3">
              <h5 className="card-title">Transcription:</h5>
              <p className="card-text">{transcription}</p>
            </div>
          </div>
        </div>
      )}
      {/* Speaker Status Display */}
      {isRecording && (
        <div className="row justify-content-center mb-4">
          <div className="col-auto">
            <p className="mb-1">
              Status:{" "}
              <strong>{isSpeaking ? "Person 1 is speaking" : "Silence"}</strong>
            </p>
            <p className="mb-1">
              Subject: <strong>Car</strong>
            </p>
            <p className="mb-1">
              Emotional State: <strong>Happy</strong>
            </p>
          </div>
        </div>
      )}

      {/* Your existing visualization component */}
      {mediaRecorder && (
        <div className="row justify-content-center">
          <div className="col-auto">
            <LiveAudioVisualizer
              mediaRecorder={mediaRecorder}
              width={500}
              height={200}
              barColor="rgba(2, 21, 86, 1)"
              minDecibels={-85}
              smoothingTimeConstant={0.3}
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default Visualizer;
import React, { useState, useRef, useCallback, useEffect } from "react";

const useMediaRecorder = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordedChunks, setRecordedChunks] = useState([]);
  const mediaRecorderRef = useRef(null);
  const streamRef = useRef(null);

  const setupRecorder = async () => {
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: {
        channelCount: 1,
        sampleRate: 48000,
      },
    });

    streamRef.current = stream;

    const recorder = new MediaRecorder(stream, {
      mimeType: "audio/webm;codecs=opus",
      bitsPerSecond: 128000,
    });

    recorder.ondataavailable = (event) => {
      if (event.data && event.data.size > 0) {
        setRecordedChunks((prev) => [...prev, event.data]);
      }
    };

    return recorder;
  };

  const resetRecording = useCallback(async () => {
    if (mediaRecorderRef.current) {
      mediaRecorderRef.current.stop();
      streamRef.current?.getTracks().forEach((track) => track.stop());
      setRecordedChunks([]);

      const newRecorder = await setupRecorder();
      mediaRecorderRef.current = newRecorder;
      newRecorder.start(2000);
    }
  }, []);

  const startRecording = async () => {
    try {
      const recorder = await setupRecorder();
      mediaRecorderRef.current = recorder;
      recorder.start(2000);
      setIsRecording(true);
    } catch (err) {
      console.error("MediaRecorder error:", err);
    }
  };

  const stopRecording = useCallback(() => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      streamRef.current?.getTracks().forEach((track) => track.stop());
      setIsRecording(false);
      setRecordedChunks([]);
    }
  }, [isRecording]);

  return {
    isRecording,
    startRecording,
    stopRecording,
    recordedChunks,
    mediaRecorder: mediaRecorderRef.current,
    resetRecording,
  };
};

export { useMediaRecorder };
const express = require("express");
const speech = require("@google-cloud/speech");
const multer = require("multer");
const path = require("path");

const app = express();
const upload = multer();
const cors = require("cors");
app.use(cors());

const credentials = require(path.join(
  __dirname,
  "../cred.json"
));
const speechClient = new speech.SpeechClient({ credentials });

app.post("/transcribe", upload.single("audio"), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: "No audio file provided" });
    }

    console.log("Received audio size:", req.file.buffer.length);

    // Smaller buffer size limit
    // if (req.file.buffer.length > 100000) {
    //   return res.json({ transcription: "çok büyük" });
    // }

    const audioBytes = req.file.buffer.toString("base64");

    const config = {
      encoding: "WEBM_OPUS",
      sampleRateHertz: 48000,
      languageCode: "en-US",
      model: "default",
      enableAutomaticPunctuation: true,
      useEnhanced: true,
      enableWordConfidence: true,
      enableWordTimeOffsets: true,
      maxAlternatives: 1,
    };

    const audio = {
      content: audioBytes,
    };

    const request = {
      config,
      audio,
    };

    console.log("Sending request to Google Speech API");
    const [response] = await speechClient.recognize(request);
    console.log("Raw response:", response);
    if (!response.results || response.results.length === 0) {
      console.log("No speech detected in audio");
      return res.json({ transcription: "" });
    }

    let transcription = "";
    response.results.forEach((result) => {
      const alternative = result.alternatives[0];
      if (alternative.confidence > 0.8) {
        transcription += alternative.transcript + " ";
      }
    });

    console.log("Final transcription:", transcription.trim());
    return res.json({ transcription: transcription.trim() });
  } catch (error) {
    console.error("API Error:", error);
    return res.status(500).json({ error: error.message });
  }
});

module.exports = app;

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

How to run Vue (Vue Cli/webpack) monorep sub app from root

My app is a simple monorepo structured like so:

root/
|--package.json
|--shared/
  |--configs/
    |--.eslintrc.js
    |--tsconfig.json
  |--types/
  |--ui-components/
|--project1/
   |--src/
      |--App.vue
      |--main.ts
   |--.eslintrc.js
   |--package.json
   |--project1.code-workspace
   |--tsconfig.json
   |--vue.config.js
|--project2/
   |--src/
      |--App.vue
      |--main.ts
   |--.eslintrc.js
   |--package.json
   |--project2.code-workspace
   |--tsconfig.json
   |--vue.config.js

I’ve been trying to use npm “workspaces” to compile the subproject’s NPM packages up into the root in the hopes I could run each project from the root with something like “cd project2 && npm start” or “npm start –prefix project2”.

Both methods result in this error:

Module not found: Error: Can't resolve './src/main.js' in '/Users/foobar/code/myapp/project2'

So is there a way to have all my NPM packages and configs in the root dir, and run each app (in those sub dirs).

Is there a native way to do this, where my root dir contains all my configs (or base configs which are extended downstream) like my package.json, vue.configs.js, .eslingrc, tsconfig ect but I can serve and build each projects in the subdirs or do I need something like Lerna?

Should my app look like this?

root/
|--package.json
|--.eslintrc.js
|--tsconfig.json
|--vue.config.js
|--shared/
  |--types/
  |--ui-components/
|--project1/
   |--src/
      |--App.vue
      |--main.ts
|--project2/
   |--src/
      |--App.vue
      |--main.ts

Problem filtering products using comparison and logical operators in JavaScript

As I filter products from an API using JavaScript’s filter() method, I cannot obtain the desired range of products defined by price checkboxes in HTML. The filering works when using an if statement like:

if ((product.price < checkboxesValues[j][1])), but there is no filtering if I try to use a range such as:

if ((product.price >= checkboxesValues[j][0]) && (product.price <= checkboxesValues[j][1])), or
if (checkboxesValues[j][0] <= product.price <= checkboxesValues[j][1]).

I am using this as a helper function. Code below:

html:

<!-- Price Checkboxes-->
         <div class="price-checkboxes">
          <h4>Price: </h4>
          <input type="checkbox" id="price1" name="price1" value="0,200">
          <label for="price1">0-200 EUR</label><br>
          <input type="checkbox" id="price2" name="price2" value="200,400">
          <label for="price2">200-400 EUR</label><br>
          <input type="checkbox" id="price3" name="price3" value="400,600">
          <label for="price3">400-600 EUR</label><br>
          <input type="checkbox" id="price4" name="price4" value="600,800">
          <label for="price4">600-800 EUR</label><br>
          <input type="checkbox" id="price5" name="price5" value="800,1000">
          <label for="price5">800-1000 EUR</label><br>
         </div>

javascript:

const isInCheckboxRange = (products) => {
    //create a NodeList of the selected checkboxes
    const checkboxes = document.querySelectorAll("input[type='checkbox']:checked");
    console.log("checkboxes: ", checkboxes);
    
    //transform the NodeList into an Array of the selected checkboxes
    const checkboxesArray = Array.from(checkboxes);
    console.log("checkboxesArray: ", checkboxesArray);
    
    //map the values in the Array into a new Array just with the selected checkboxes values in integers
    const checkboxesValues = checkboxesArray.map((checkbox) => {
        //return a number array from the previous string's value
        const stringArray = checkbox.value.split(",");
        return stringArray.map(Number);
    })
    console.log("checkboxesValues: ", checkboxesValues);

    const filteredProductPrices = products.filter((product) => {
            for (let j = 0; j < checkboxesValues.length; j++) {
                // console.log("product price: ", product.title, product.price, "checkboxesValues[j][0]: ", checkboxesValues[j][0], "checkboxesValues[j][1]: ", checkboxesValues[j][1]);

                if ((product.price < checkboxesValues[j][1])) { 
                // if ((product.price >= checkboxesValues[j][0]) && (product.price <= checkboxesValues[j][1])) {
                // if (product.price > checkboxesValues[j][0] && product.price < checkboxesValues[j][1]) {
                // if (checkboxesValues[j][0] <= product.price <= checkboxesValues[j][1]) {
                    console.log("product price: ", product.title, product.price, "checkboxesValues[j][0]: ", checkboxesValues[j][0], "checkboxesValues[j][1]: ", checkboxesValues[j][1]);
                    return true;
                }
            }
            
            return false;
    });
    console.log("Filtered Products: ", filteredProductPrices);
    return filteredProductPrices;

I tried to use the return true; statement in different parts of the nested loop but with no success.

How to change folding icon position in mxgraph

I am trying to create a graph of stacked children’s for compact layout behaviour using tree chart.

With the below configuration, it looks stacked.

var layout = new mxCompactTreeLayout(graph, true);

enter image description here

But, the folding icon is still at the bottom centre and hence the right hand side node edges are not properly aligned.

If the folding icon is on RHS vertically aligned, then it would look aligned.

Looking for something similar like Treantjs here

enter image description here

and like this:

enter image description here

Is it possible to achieve with mxgraph? Looking forward to see the configuration settings to achieve this with an example.

Horiba H550 analyzer, histogram and Diff matrix regenerating

I’m working with a Horiba H550 analyzer and need to interface it with the LIMS.
So far, all good except the histogram and diff matrix graph extracting.
Up to now all the cases (in Mindray analyzers), the analyzer throws a base64 encoded image, i will directly send it to the LIMS and when ever i want I use it in tag with src as the base64 code. (I use html and Javascript)

But in this case I get the following stream

OBX|1|ED|RBC^RBCALONGRES||FLOATLE-stream/deflate:base64^7dR/aJR1HMDxb2UWndnKOLVW7Ugt7a7MX1uS3fP9flRM3Vqa1lWWrcuaSY+1SrmWPV6382pKG4MYbcRA3CoZyCki4eEkhCPMRleYSG6IlTvCiHllNqT34z1S6KJ/+rODN9/nnvve6/u95zkepdxXo5wflH+uUpal1AKjVJb83nnFuQ0SDTSGowGf5U9XWxxbmYFujnstOzbIe59ubijVmYGQzleGNXO0+Gu0HavTVXZcM1/Hci3Maddd5duY161zbbuZu0+zFvN7dSh6hO8c15Fsnu8N6mRwiO9ebiLZkQbf2LHrTCw3xiSD4wxrmfZjZaarfKJJN002rGuyZprJtc0yfadnG/ZgCp1i3N/iiyw27McEfMtMKBoxFZkVhr2ZKnsV9mpsG7sOex12PY7DZ3GsBJ8n8VLMacTcwrz3cJuZ24L9PvNb8T9gP+2s8SF76mCdrexrG2t1sbePWW87++tmzR3Yaexd2Lux92B/ip3B3oe9H/sz7APnr38y+Dn2QexD2L3YX2F/g30Y+wj2UezvsPuwj2OfwP4B+yR2Hvsn7J+xf8EexC5g/4Z9FnsI+xzfUeKLXCZcZ2luuEJybSPEn75SuObSfuwq6Tt9tQR813DvfdJVPkrylddKKDpauBeSbiqRQuf1UpG5Qbgvkhm4Udz/jPjHCvdIsmY89k3YN2OXYt+CfSv2bdhl2AHs27EnYE/EnoR9B/ad2JOxp2DfhR3EDmHfgz0V+17sadjTsWdgz8SehV2OXYF9H/Zs7Pux52A/gB3GtrA1tsEW7LnY87DnYy/AfhB7IfYi7MXYldhV2A9hV2M/jL0Eeyn2Muzl2I9iP4YdwX4c+wnsJ7FXYD+F/TT2M9g12M9iR7Gfw16F/Tz2C9i12KuxX8Reg/0Sto29Fvtl7Few67BfxX4N+3XsddjrsWPYb2DXY7+JvQH7LY4dyX/h8H6jhE5s5Fxc7LNx1nxb0iUJ1k1IYVIDazdIxZwk6ycltnQTe9gkmdoU+0iJct5hL+9eeAb8hy8nPHzuc+ZClpfj1eOe51lRRiupiXpI8X+eQNWUoE46SL/SGPZ+Ny2iWkrwm1poK8c7Gfczfsl4lL6nU7wvMP7OOMRI6g86w/Ego/v5j9RHhzl3iA7QXt7vYtxetJ224jpqMyNrqnqyqYaW00IK00yaQmU0lkbTSDrH3k9RP33tPYv3Upo+oQ5qpSZKUZzW0xpaSY+Y4jPcohkU9K5RKY2jEhpFI0zx+p3hOp6kfvqWer1ru4d20EfUQa3edU+RQ2u9e+FWTZbXVO8+uZXo4n1z67f+qudvdVyUM0zWMKl/6Z/+Z5f87/5/DfP6Ew==|HISTOGRAM|FLOATLE-stream/deflate:base64^Y2AAgW5nMMUg5gIkHEAsAA==||||F|||||technician

it seems it is not working directly as base64 image.
I tried as follows.

const encodedData = "7dR/aJR1HMDxb2UWndnKOLVW7Ugt7a7MX1uS3fP9flRM3Vqa1lWWrcuaSY+1SrmWPV6382pKG4MYbcRA3CoZyCki4eEkhCPMRleYSG6IlTvCiHllNqT34z1S6KJ/+rODN9/nnvve6/u95zkepdxXo5wflH+uUpal1AKjVJb83nnFuQ0SDTSGowGf5U9XWxxbmYFujnstOzbIe59ubijVmYGQzleGNXO0+Gu0HavTVXZcM1/Hci3Maddd5duY161zbbuZu0+zFvN7dSh6hO8c15Fsnu8N6mRwiO9ebiLZkQbf2LHrTCw3xiSD4wxrmfZjZaarfKJJN002rGuyZprJtc0yfadnG/ZgCp1i3N/iiyw27McEfMtMKBoxFZkVhr2ZKnsV9mpsG7sOex12PY7DZ3GsBJ8n8VLMacTcwrz3cJuZ24L9PvNb8T9gP+2s8SF76mCdrexrG2t1sbePWW87++tmzR3Yaexd2Lux92B/ip3B3oe9H/sz7APnr38y+Dn2QexD2L3YX2F/g30Y+wj2UezvsPuwj2OfwP4B+yR2Hvsn7J+xf8EexC5g/4Z9FnsI+xzfUeKLXCZcZ2luuEJybSPEn75SuObSfuwq6Tt9tQR813DvfdJVPkrylddKKDpauBeSbiqRQuf1UpG5Qbgvkhm4Udz/jPjHCvdIsmY89k3YN2OXYt+CfSv2bdhl2AHs27EnYE/EnoR9B/ad2JOxp2DfhR3EDmHfgz0V+17sadjTsWdgz8SehV2OXYF9H/Zs7Pux52A/gB3GtrA1tsEW7LnY87DnYy/AfhB7IfYi7MXYldhV2A9hV2M/jL0Eeyn2Muzl2I9iP4YdwX4c+wnsJ7FXYD+F/TT2M9g12M9iR7Gfw16F/Tz2C9i12KuxX8Reg/0Sto29Fvtl7Few67BfxX4N+3XsddjrsWPYb2DXY7+JvQH7LY4dyX/h8H6jhE5s5Fxc7LNx1nxb0iUJ1k1IYVIDazdIxZwk6ycltnQTe9gkmdoU+0iJct5hL+9eeAb8hy8nPHzuc+ZClpfj1eOe51lRRiupiXpI8X+eQNWUoE46SL/SGPZ+Ny2iWkrwm1poK8c7Gfczfsl4lL6nU7wvMP7OOMRI6g86w/Ego/v5j9RHhzl3iA7QXt7vYtxetJ224jpqMyNrqnqyqYaW00IK00yaQmU0lkbTSDrH3k9RP33tPYv3Upo+oQ5qpSZKUZzW0xpaSY+Y4jPcohkU9K5RKY2jEhpFI0zx+p3hOp6kfvqWer1ru4d20EfUQa3edU+RQ2u9e+FWTZbXVO8+uZXo4n1z67f+qudvdVyUM0zWMKl/6Z/+Z5f87/5/DfP6Ew==";

 const binaryData = atob(encodedData);
 const buffer = new ArrayBuffer(binaryData.length);
    const view = new Uint8Array(buffer);
    for (let i = 0; i < binaryData.length; i++) {
        view[i] = binaryData.charCodeAt(i);
    }
const decompressedData = pako.inflate(buffer);

But it fails all the time with a “Decompression failed: unknown compression method” error or a “header error”. Gzip also the same issue.

I tried the ChatGPT but it’s all attempts made the same thing.
I got following solution in VB and Python but I don’t know how to interpret it in Javascript as have no knowledge in VB or Python.

https://www.vbforums.com/showthread.php?868881-Base64-and-the

Following is a Python solution

Image Conversion From Base64 – FLOATLE-Stream

Any clue please?

It’s better if I can get the graph as a base64 stream.

Performance degrade on JSObject after 2^23 items

I’m having trouble understanding the code below. Its performance worsens significantly after 2^23 (8,388,608) items. I was thinking it might have something to do with how JSObject is implemented, but it turns out that if I change the string keys to some sort of hashes, the performance is actually pretty good.

I want to understand how V8 works under the hood with this example:

function foo() {
    const result = Object.create(null);
    for (let i = 0; i < 25_000_000; i += 1) {
        console.time(`Prop ${i}`);
        result[`prop_${i}`] = i + (Math.random() * 25_000_000);
        console.timeEnd(`Prop ${i}`);
    }
    return result;
}


const a = foo();

%DebugPrint(a);

console.log(a[`prop_24000000`]);
console.log(Object.keys(a).length);

To run it

$ node --allow-natives-syntax file.js

The recorded time is around 0.001 ms before 2^23 items, but after that, it increases to approximately 1.5 seconds per iteration.

I also want to profile it to see if the theories are correct. If you have any theories, please let me know how I can profile it.

Thanks in advance!

vscode extension – promise handling

I am on the way to write my first vscode extension in js.
I currently face a problem, that I do not understand. Most likely because of too little knowledge about js.

So this is my code in extension.js

const mypromise = vscode.window.activeTextEditor.edit((editBuilder) => {
    editBuilder.insert(mysecondpos,"nhello worldn");
    }).then(function() { console.log("success"); },
    function() { console.log("fail");})

This shall insert the line “hello world” at mysecondpos, which is of type vscode.Position.

And it works. The line appears, when I execute the extension using Extension Development Host.
But when I close the Extension Development Host window, I get errors (see image for better visibility of what the errors are).

What I tried and what I expected

I added the two callback functions to .then in the above code in order to react to a rejected promise. Although I do not understand, why the promise gets the state rejected. because the change succeeded.

It seems to me that the whole operation is not done, when I close the Extension Development Host window. That it still waits for something or so. But I expected that I can simply close the window without any error.

“Uncaught (in promise) TypeError: …img is undefined” when using @sveltejs/enhanced-img with dynamic image URLs

I’m encountering an issue using @sveltejs/enhanced-img in my Svelte project. I’ve installed it via npm install –save-dev @sveltejs/enhanced-img and configured it in vite.config.js.

My setup involves an array of question objects, each containing an image URL. I’m trying to dynamically render these images using enhanced:img.

Here are examples of how I’m structuring my data:

const PERGUNTAS = [
{
    pergunta: 'question?',
    id: 'name',
    type: 'text',
    URLimagem: '/static/nome.jpg', // First attempt: with /static/
    resposta: 'answer'
},
{
    pergunta: 'question',
    id: 'nome',
    type: 'text',
    URLimagem: '/nome.jpg', // Second attempt: without /static/
    resposta: 'answer'
},

I’ve tried both including /static/ in the path and omitting it. When I remove the enhanced:img tag and just use a standard tag, the images load correctly.

I’ve also attempted using the import syntax with the ?enhanced query parameter, like this: import image from '/link/to/image.jpg?enhanced', but I get the same result.

The error I’m consistently getting in the console is:

Uncaught (in promise) TypeError: pergunta().URLimagem.img is undefined

This error suggests that pergunta().URLimagem.img is undefined. I understand that the image should be undefined initially until the user provides the correct answer in the input field. The problem is that even after providing the correct answer, which should trigger the image display, I still receive this error.

Here’s the relevant part of my Svelte component:

<enhanced:img src={pergunta.URLimagem} alt="fantasma" class="fantasma" />

My vite.config.js is configured correctly (I’ve double-checked the paths).

In addition to the image issue, I’m also experiencing a problem with the dynamic rendering of the answer text. The answer is displayed dynamically as the user types. However, when the user finishes typing the complete answer, the last letter is missing. For example, if the answer is “answer”, it only displays “answe”. This indicates that the component stops updating before rendering the final character.

Crucially, I’ve discovered that both problems are resolved when I remove the enhanced:img tag and use a standard tag.

Is @sveltejs/enhanced-img not designed to handle dynamic image URLs in this way? Or am I missing something obvious? Any help would be greatly appreciated.

d3.js error in React application (undefined is not an object (evaluating ‘this.document’))

I’m working on a project that includes a crossfiltering dashboard for data analysis. Initially, I used Chart.js, but it doesn’t natively support crossfiltering functionality.

After some research, I discovered the dc.js library and decided to implement it in my project. However, I’m encountering an error when the page first loads, and I’m finding it difficult to resolve the issue.

undefined is not an object (evaluating 'this.document')

Here is the code where I implemented dc.js:

import { barChart } from "dc";
import crossfilter from "crossfilter";

export class Dataset {
  data = [];
  rows = [];
  filters = [];
  columns = [];
  values = {};
  dimension = {};

  constructor(data, { rows, columns, filters, values }) {
    this.data = data;
    this.rows = rows;
    this.columns = columns;
    this.filters = filters;
    this.values = values;
  }

  get crossFilter() {
    return crossfilter(this.data);
  }

  run() {
    if (this.rows.length) {
      this.dimension.rows = [];
      this.dimension.rows.push(
        this.crossFilter.dimension((d) => {
          return `${this.rows.map((row) => `${row}=${d[row]}`).join(";")}`;
        })
      );
    }
    if (this.columns.length) {
      this.dimension.columns = [];
      this.dimension.columns.push(
        this.crossFilter.dimension((d) => {
          return `${this.columns
            .map((column) => `${column}=${d[column]}`)
            .join(";")}`;
        })
      );
    }

    for (let index = 0; index < this.rows.length; index++) {
      const row = this.rows[index];
      const dimensionRow = this.dimension.rows[index];
      this.dimension.values = dimensionRow.group().reduceCount((d) => d[row]);
    }
  }

  createChart(element) {
    const chart = new barChart(element);
    chart.width(780).height(300);
  }
}

App

  useEffect(() => {
    const rowValues = {};
    for (let key in values) {
      if (rows.includes(key)) {
        rowValues[key] = values[key];
      }
    }

    const dataset = new Dataset(data.current, { rows });
    dataset.run();
    console.log(dataset.dimension);
    setValue(rowValues);
  }, [rows]);

Please help me, solve this problem. Thanks advance!

Why does the URL constructor not decode the username/password?

URL decodes searchParams:

> [...new URL('http://localhost?foo%40=bar').searchParams][0]
['foo@', 'bar']

Yet for some reason, it doesn’t decode username/password:

> new URL('http://jimbo%40gmail.com:%40wesome@localhost').username
'jimbo%40gmail.com'
> new URL('http://jimbo%40gmail.com:%40wesome@localhost').password
'%40wesome'

Obviously I know how to work around this, but does anyone know the reason why it doesn’t decode them?

RFC 3986 section 3.2.1 specifically indicates that the username/password of a URI may be percent-encoded:

userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )

So I would assume this is a bug if it were not a well-standardized API.

How can i allow my react frontend that is deployed on GitHub pages to access localhost backend api?

i am trying to deploy my react app to GitHub pages without a custom url. Almost everything works well and the page is successfully deployed. Although, when i go to the web address, it seems that the page does not communicate with the api. After checking the console these 3 errors and 1 warning show up:

[Warning] [blocked] The page at https://ambaks.github.io/auction-app/ requested insecure content from http://localhost:8000/emails. This content was blocked and must (main.93af0b37.js, line 2)

[Error] Not allowed to request resource
(anonymous function) (main.93af0b37.js:2:210042)
Promise
(anonymous function) (main.93af0b37.js:2:208038)
St (main.93af0b37.js:2:218033)
_request (main.93af0b37.js:2:221077)
(anonymous function) (main.93af0b37.js:2:219507)
request (main.93af0b37.js:2:219781)
(anonymous function) (main.93af0b37.js:2:224798)
(anonymous function) (main.93af0b37.js:2:224872)
(anonymous function) (main.93af0b37.js:2:224873)
Ii (main.93af0b37.js:2:84015)
Eu (main.93af0b37.js:2:99867)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:100549)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:99888)
tc (main.93af0b37.js:2:126626)
(anonymous function) (main.93af0b37.js:2:124005)
T (main.93af0b37.js:2:180662)

[Error] XMLHttpRequest cannot load http://localhost:8000/emails due to access control checks.
(anonymous function) (main.93af0b37.js:2:210042)
Promise
(anonymous function) (main.93af0b37.js:2:208038)
St (main.93af0b37.js:2:218033)
_request (main.93af0b37.js:2:221077)
(anonymous function) (main.93af0b37.js:2:219507)
request (main.93af0b37.js:2:219781)
(anonymous function) (main.93af0b37.js:2:224798)
(anonymous function) (main.93af0b37.js:2:224872)
(anonymous function) (main.93af0b37.js:2:224873)
Ii (main.93af0b37.js:2:84015)
Eu (main.93af0b37.js:2:99867)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:100549)
Su (main.93af0b37.js:2:99751)
Eu (main.93af0b37.js:2:99888)
tc (main.93af0b37.js:2:126626)
(anonymous function) (main.93af0b37.js:2:124005)
T (main.93af0b37.js:2:180662)

[Error] Error fetching emails: – Q {stack: “@https://ambaks.github.io/auction-app/static/js/ma…o/auction-app/static/js/main.93af0b37.js:2:219600”, message: “Network Error”, name: “AxiosError”, …}
Q {stack: “@https://ambaks.github.io/auction-app/static/js/ma…o/auction-app/static/js/main.93af0b37.js:2:219600”, message: “Network Error”, name: “AxiosError”, code: “ERR_NETWORK”, config: Object, …}Q
(anonymous function) (main.93af0b37.js:2:224842)

I tried creating a custom certificate and running my localhost on server like they did at this link but it didn’t work for me.

Here is my backend code:
database.py:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import declarative_base

URL_DATABASE = 'sqlite:///./emails.db'

engine = create_engine(URL_DATABASE, connect_args={"check_same_thread": False})

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

main.py:

'''
FastAPI app
'''
from database import Base
from fastapi import FastAPI, HTTPException, Depends
from typing import Annotated, List
from sqlalchemy.orm import Session
from pydantic import BaseModel
from database import SessionLocal, engine
import models
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    '*'
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*']
)

class EmailBase(BaseModel):
    email: str

class EmailModel(EmailBase):
    id: int

    class Config:
        orm_mode=True



def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()



db_dependency = Annotated[Session, Depends(get_db)]

Base.metadata.create_all(bind=engine)


@app.post('/emails', response_model=EmailModel)
async def create_email(email: EmailBase, db: db_dependency):
    db_email = models.Email(**email.model_dump())
    db.add(db_email)
    db.commit()
    db.refresh(db_email)
    return db_email


@app.get('/emails', response_model=List[EmailModel])
async def read_emails(db: db_dependency, skip: int = 0, limit: int = 100):
    emails = db.query(models.Email).offset(skip).limit(limit).all()
    return emails

models.py:

from database import Base
from sqlalchemy import Column, Integer, String

class Email(Base):
    __tablename__ = 'emails'

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String)

and here is the code for my react frontend:

api.js:

import axios from 'axios';

const api = axios.create({
    baseURL: 'https://localhost:8000'
});

// Export axios instance
export default api;

app.js:

import React, { useState, useEffect } from 'react';
import api from './api';

const App = () => {
  const [emails, setEmails] = useState([]);
  const [formData, setFormData] = useState({ email: '' });

  useEffect(() => {
    const fetchEmails = async () => {
      try {
        const response = await api.get('/emails'); // Fetch emails
        setEmails(response.data);
      } catch (error) {
        console.error('Error fetching emails:', error);
      }
    };

    fetchEmails();
  }, []);

  const handleFormSubmit = async (event) => {
    event.preventDefault();
    try {
      await api.post('/emails', formData); // Submit email
      setFormData({ email: '' });
      const response = await api.get('/emails'); // Refresh email list
      setEmails(response.data);
    } catch (error) {
      console.error('Error submitting email:', error);
    }
  };

  const handleInputChange = (event) => {
    setFormData({ email: event.target.value });
  };

  return (
    <div >
      <nav className="navbar navbar-dark bg-primary">
        <div className="container-fluid">
          <a className="navbar-brand" href="#">
            Naia App
          </a>
        </div>
      </nav>
      <div className="container mt-4">
        <form onSubmit={handleFormSubmit}>
          <div className="mb-3">
            <label htmlFor="emailInput" className="form-label">Email</label>
            <input
              type="email"
              className="form-control"
              id="emailInput"
              value={formData.email}
              onChange={handleInputChange}
              required
            />
          </div>
          <button type="submit" className="btn btn-primary">Add Email</button>
        </form>
      </div>
    </div>
  );
}

export default App;

This is what my package.json looks like:

{
  "name": "react-frontend",
  "homepage": "https://ambaks.github.io/auction-app",
  "version": "0.1.0",
  "private": false,
  "dependencies": {
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "axios": "^1.7.9",
    "gh-pages": "^6.2.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

and this is my index.html:

<!doctype html>
<html lang="en"><head><meta charset="utf-8"/><link rel="icon" href="./auction-app/favicon.ico"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"><link rel="apple-touch-icon" href="./auction-app/logo192.png"/><link rel="manifest" href="./auction-app/manifest.json"/><title>React App</title><script defer="defer" src="./auction-app/static/js/main.25947243.js"></script><link href="./auction-app/static/css/main.e6c13ad2.css" rel="stylesheet"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script></body></html>

Thank you all so much for your help!

Why is this frame.onload not triggered?

I have a web page that calls an onload method myonload as a final line in the <script> section of the header:

...
window.onload = myonload;
</script>
</head>

The document has an iframe called MainFrame. Inside myonload, I have a function that checks if this iframe is loaded with

function myonload() {
    frame = document.getElementById("MainFrame")
    frame.onload = function(e) { ... }
    ...
}

Everything works as expected, except that the frame.onload is NOT triggered when I press the browser refresh button. It does work if I refresh the page with Ctrl-R`, though.

Now, if I replace

 window.onload = myonload;

with

 document.addEventListener('DOMContentLoaded', myonload);

the thing seems to work well.

Why is that, and how to handle the refresh properly?

How to automatically scroll down to the bottom of a div in AngularJS

I have a chat application in AngularJS im just trying to scroll down all the way to the bottom like most chat apps do. i tried the native element.scrolltop attribute but no success

code
search.component.ts

import { Component,  OnInit,ViewChild, ElementRef } from '@angular/core';
import { CommonModule } from '@angular/common';
...


@Component({
...
})
export class SearchComponent{
..
  selectedMessages: any[] = []
...
  @ViewChild('inboxChat',{static:true}) inboxChat?: ElementRef<HTMLDivElement>;

 constructor(private socketService: SearchService,private router: Router) {
...
}
 ngOnInit() { 

      if (this.inboxChat?.nativeElement){
        this.inboxChat.nativeElement.scrollTop = this.inboxChat.nativeElement.scrollHeight
        }
}

  ngAfterViewInit() {
    // Accessing the DOM element directly
    console.log(this.inboxChat?.nativeElement);

    // Modifying the DOM element
    if(this.inboxChat?.nativeElement)
    this.inboxChat.nativeElement.scrollTop = this.inboxChat?.nativeElement.scrollHeight;
    
  }

}

search.component.html

 <div  class="mesgs" *ngIf="selectedMessages !== []" >
              <div #inboxChat class="msg_history">
                ...
           
            </div>
          </div>

search.component.css

...
.msg_history {
  height: 516px;
  overflow-y: auto;
}

class .msgs doesn’t have overflow-y at all and i tried with that class selected as well

React Swiper does not rendering slides when passing slides via children prop

I am trying to build a carousel using swiper, I am trying to pass the SwiperSlide as children of the Swiper in this case it does not render the slides in the browser

here is how I tried:

MyCarousel.tsx:

import React from 'react';
import { Swiper } from 'swiper/react';
import 'swiper/css';

interface ComponentProps {
  children: ReactNode
}

function MyCarousel({children}: ComponentProps){
  return (
    <Swiper loop={true} spaceBetween={50} slidesPerView={1}>
      {children}
    </Swiper>
  );
};

export default MyCarousel;

MySlides.tsx:

import React from 'react'
import { SwiperSlide } from 'swiper/react'

function MySlides({ slides }: ComponentProps) {

  return (
    <>
      {slides.map((slide) => (
        <SwiperSlide className="h-full" key={slide.id}>
          <div
            className="h-full bg-cover bg-center bg-no-repeat blur-3xl"
            style={{ backgroundImage: `url(${slide.src})` }}
          ></div>
          <div className="absolute inset-0 flex h-full justify-center">
            <img src={slide.src} alt={slide.src} />
          </div>
        </SwiperSlide>
      ))}
    </>
  )
}

MyPage.tsx:

import React from 'react'
import MySlidesfrom '@components/my-slides'

function MyPage() {

  const slides = [
    { id: 1, src: 'my-image-1.jpg' },
    { id: 2, src: 'my-image-2.jpg' },
    { id: 3, src: 'my-image-3.jpg' },
  ];

  return (
    <div>
      <h1>My Page</h1>
      <CarouselProvider>
        <MySlides slides={slides} />
      </CarouselProvider>
    </div>
  );
};

The above way is not working. It is not working the slides in the DOM as you can see in the screenshot the swiper-wrapper is empty
swiper-wrapper div is empty in the DOM

If I modify MyPage.tsx this way it works as it should-

import React from 'react'

function MyPage() {

  const slides = [
    { id: 1, src: 'my-image-1.jpg' },
    { id: 2, src: 'my-image-2.jpg' },
    { id: 3, src: 'my-image-3.jpg' },
  ];

  return (
    <div>
      <h1>My Page</h1>
      <CarouselProvider>
        {slides.map((slide) => (
          <SwiperSlide className="h-full" key={slide.id}>
            <div
              className="h-full bg-cover bg-center bg-no-repeat blur-3xl"
              style={{ backgroundImage: `url(${slide.src})` }}
            ></div>
            <div className="absolute inset-0 flex h-full justify-center">
              <img src={slide.src} alt={slide.src} />
            </div>
          </SwiperSlide>
        ))}
      </CarouselProvider>
    </div>
  );
};

I am using

  • “react”: “^18.3.1”,
  • “swiper”: “^11.1.15”,

Thank you so much for your attention and participation.

useEffect() with empty dependency array not running on page refresh

I am trying to do some session verification when my page is initially loaded. The AuthenticationRequiredComponent is used as a wrapper for other components that require authentication. If users are not logged in, they should be redirected to the login page. This component has a useEffect callback defined with an empty dependency array, because it subscribes to an auth state change (it is using Firebase Auth). If I go through the whole process of logging in to my website, and get to a page that uses this wrapper, the useEffect is called correctly. However, if I am in a page that uses this wrapper and I hit refresh or if I navigate directly to the url of a page that uses this wrapper, the useEffect is not being called, which results in the page not working correctly. The project is fairly large, so I cannot post the entire code. I will add pseudocode of some of the parent elements for structure:

export const AuthenticationRequiredComponent = ({ children }) => {
    const { session, dispatch } = useContext (SessionContext);
    const navigate = useNavigate ();

    const [ loadingLogin, setLoadingLogin ] = useState (false);

    /* This is the useEffect() that is not running */
    useEffect (() => {
        return isLoggedIn (setLoadingLogin, doWithUser, handleError);
    }, []);

    useEffect (() => {
        if (!session.loggedIn) {
            navigate ("/login");
        }
    }, [ session ]);

    function doWithUser ({ user, token }) {
        dispatch ({ type: "login", user, token: token });
    }

    function handleError (err) {
        console.error (err);
        dispatch ({ type: "logout" });
    }

    return children;
};

/* This is the parent component */
const MainComponent = () => {
    return <AuthenticationRequiredComponent>
        <Navbar />

        <Outlet />
    </AuthenticationRequiredComponent>
}

/* This creates a "route" object, which is then passed to an upper level array,
   and eventually a router is created through `createBrowserRouter`*/
export const businessRoute = {
    path: ":businessId",
    element: <MainComponent />,
    errorElement: <>Error</>,
    children: [
        homeRoute,
        ...
    ]
};

I read the documentation on useEffect, and it says that effects with empty dependency arrays are only run after the initial render. Why then are they not triggered when I refresh the page? When does this initial render happen? Looking around I also noticed that there are other components whose useEffect with empty dependency arrays are not being called on similar scenarios. I would appreciate any help on figuring out why this is happening.