Skip to main content

Posts

Showing posts with the label Active questions tagged javascript - Stack Overflow

Line 22:6: React Hook useEffect has a missing dependency: 'auth.token'. Either include it or remove the dependency array

Error webpackHotDevClient.js:115 ./src/components/Layout/Routes/private.js Line 22:6: React Hook useEffect has a missing dependency: 'auth.token'. Either include it or remove the dependency array Line 22:7: React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked react-hooks/exhaustive-deps Private.js import { useState, useEffect } from "react"; import { useAuth } from "../../../context/auth"; import React from "react"; import { Outlet } from "react-router-dom"; import axios from "axios"; import Spinner from "../../spinner"; export default function PrivateRoute() { const [ok, setOk] = useState(false); const [auth] = useAuth(); useEffect(() => { const authCheck = async () => { const res = await axios.get("/api/v1/auth/user-auth"); if (res.data.ok) { setOk(true); } else {

Make GPT (Store) instructions output exact JavaScript code pattern answer [closed]

I have created a GPT app in the store, that outputs JavaScript Web Components. Since GPT is trained on old Web Components GPT is biased in its output. For example, because older blogs and even MDN say "use super() first in the constructor" , GPT outputs: constructor() { super(); const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props); let shadow = this.attachShadow({ mode: 'open' }); shadow.append( createElement( "style", innerHTML = `` )); } But uou can use JavaScript before super() because it sets and returns the this scope. I want it to write: constructor() { const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props); super() .attachShadow({ mode: 'open' }) .append( createElement( "style", innerHTML = `` )); } These are my instructions (related to this part of the code): * Include a `createElement(tag, props={})=>Object.assig

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory - removing sourcemaps still fails

Our team has a CRA application and we are using the following script to build locally and in bitbucket pipelines node --max-old-space-size=8192 scripts/build.js We are all getting this error now with our source code FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory 1: 0x111336665 node::Abort() (.cold.1) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 2: 0x11002f1c9 node::Abort() [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 3: 0x11002f3ae node::OOMErrorHandler(char const*, bool) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 4: 0x1101a41d0 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 5: 0x1101a4193 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/Users/apple/.nvm/versions/node/v16.20.0/bin/node] 6: 0x1103458e5 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/Users/apple/.nvm/versions/

How do I show a error message if no product is found?

I have a search.js file that reads a json file and retrieves information about some products, and then displays it in the page. I am trying to show a error message if no product is found when searching, and this part is almost working. If a search for a non-existent product, the error message appears correctly: enter image description here The problem is, if I search for a product that the name isn't similar to another one, the error still appears.. for example: enter image description here enter image description here Json file structure is like this: [ { "nome": "Carro", "apelido": "ft.car", "desc": "descrição", "img": "/img/carro.png", "link": "/pag/carro.html" }, { "nome": "Carreta Bi-Trem", "apelido": "ft.big.truck", "desc": "descrição",

How do I correctly resume a session for a user?

I've just started learning next.js (TypeScript) and I've run into a problem. I need to authorize a user to restore his session. The authorization key is a token that is stored in cookies. How to implement this task correctly? At the moment, I have simply created a component in which I have embedded RootLayout , and in the component itself I am already executing an API request to search for a user by token, but with this approach I get various errors. Perhaps there are some other options? 'use client'; import { fetcher } from '@/helpers/fetcher'; import { useUserStore } from '@/store/user'; import { QueryCache, useQuery } from '@tanstack/react-query'; import { deleteCookie, getCookie } from 'cookies-next'; import { useEffect } from 'react'; export default function Auth() { const { user, setUser } = useUserStore(); const rememberToken = getCookie('remember_token'); if (user == null && rememberToken !=

Encode audio data to string (Flask) and decode it (Javascript)

I have a Python Flask app with the method shown below. In the method I'm synthesizing voice from text using Azure text to speech. @app.route("/retrieve_speech", methods=['POST']) def retrieve_speech(): text= request.form.get('text') start = time.time() speech_key = "my key" speech_region = "my region" speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=speech_region) speech_config.endpoint_id = "my endpoint" speech_config.speech_synthesis_voice_name = "voice name" speech_config.set_speech_synthesis_output_format( speechsdk.SpeechSynthesisOutputFormat.Audio24Khz160KBitRateMonoMp3) synthesizer = speechsdk.SpeechSynthesizer(speech_config=speech_config, audio_config=None) result = synthesizer.speak_text_async(text=text).get() if result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted: # Convert to wav audio = AudioSegment

Recommend extraction api/library for better extracting all information in a pdf using Nodejs [closed]

What library or API is the best at extracting information in a PDF file in Nodejs. Things like text (how they properly are structured), images (couple with information on images like text if it got one), table etc... I'm aware of libraries like pdf-extract and the rest but most of them capabilities are limited to just extracting text and pretty much can't do other stuffs I mentioned above. Also, I don't want to mix many different libraries to do the tricks. So what do you suggest? Via Active questions tagged javascript - Stack Overflow https://ift.tt/aTZwn7q

Injecting React components into webpages using content scripts in browser extensions

I am creating a React-based browser extension and I am trying to inject a React component into webpages using content scripts. However, it seems like using React or ReactDOM prevents the content script from loading. Is there any to get around this issue? This is the code that I currently have. It seems like the content script only loads when React and ReactDOM is not used since nothing is logged to the console. import NavBar from "./NavBar"; import React from 'react'; import ReactDOM from 'react-dom'; console.log('Content script is running'); const container = document.createElement('div'); document.body.appendChild(container); ReactDOM.render(<NavBar />, container); Via Active questions tagged javascript - Stack Overflow https://ift.tt/yZtDo8N

Cannot read properties of null in SPA javascript when reading a form in another route

I have the below single page application, but when I go to the login route, and submit, the event listener for the form is not triggered And I get this error : Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at login?session%5Bemail%5D=fdf%40gmail.com&session%5Bpassword%5D=dfdf&session%5Bremember_me%5D=0:34:6 This is the home page <!DOCTYPE html> <html> <head> <title>Vanilla SPA Router</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="css/styles.css" /> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.5.95/css/materialdesignicons.min.css" rel="stylesheet" /> </head> <body> <div id="root"> <nav id="main-nav" class="sidebar"> <a href="/" onclick="route()">Home<

Javascript parse RSS which includes German characters

I am trying to load rss which has German characters included (ö, ä, ü...) xhrRequest.responseText already contains converted characters (\u00f ...) Without manually replacing is there to force right encoding so original characters stay visible? var url = 'https://apolut.net/feed/podcast/' xhrRequest = new XMLHttpRequest(); xhrRequest.onreadystatechange = function() { if (xhrRequest.readyState == 4) { } } xhrRequest.onerror = function(e) { }; xhrRequest.open('GET', url); xhrRequest.setRequestHeader("Content-Type", "text/xml"); xhrRequest.send(); I do have utf on the top of page: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> Via Active questions tagged javascript - Stack Overflow https://ift.tt/Aosi8g1

Are timing requirements in webRtc between calling setRemoteDescription and addIceCandidate?

I have implemented webrtc in 2 browsers that physically work on one local machine (one browser I will call as "local", another - "remote"). The browser - Firefox 112.0.1, TURN, STUN servers are not used. All strings (offer, answer, ice candidates) are transferred from one to another browser manually (slow transfer - via copy and paste). "Remote" gets an offer from the "local" and processes it by rtc2_RegisterRemoteOffer (see code below). This function creates answer of the "remote". Then: (1) the negotiationneeded event fired on the "remote", (2) because of (1) "remote" creates offer and generates it's own ice candidates (up to here neither "local" nor "remote" ice candidates I didn't transfer to each other). (3) Then after few seconds on the "remote" iceconnectionstate fired with the status failed . The questions are: What may be a reason of iceconnectionstate gets faile

Form is returning null without any reason [closed]

thanks to give me your time. I actually coding a login page but i can't write form.addEventListener() When i console.log(form) it return null and i don't know why For the js side : const form = document.getElementById("form"); console.log(form) form.addEventListener('submit', (event) => { event.preventDefault console.log(event) console.log(form) }) For the html side : [...] <form id="form"> <label for="email"> Entrez votre Email : </label> <input id="email" type="email" name="email" placeholder="Email ..." required> <label for="mdp"> Entrez votre Mot de Passe : </label> <input type="password" name="password" id="mdp" placeholder="Mot De Passe ..." required> <input type="submit" name="envoyer" id=&quo

React Native npx create-react-app Problem

My PowerShell(Terminal) Warn, i don't used npm install or any one just tried npx create-react-app NKE command: PS C:\Users\berk.BERK-PC\React Native> npx create-react-app NKE npm WARN using --force Recommended protections disabled. npm WARN using --force Recommended protections disabled. npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\Users\berk.BERK-PC\React Native\'~ npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or directory, lstat 'C:\Users\berk.BERK-PC\React Native\'~' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent npm ERR! A complete log of this run can be found in: C:\Users\berk.BERK-PC\AppData\Local\npm-cache\_logs\2023-12-28T21_08_04_536Z-debug-0.log PS C:\Users\berk.BERK-PC\React Native> The Loc File: 0 verbose cli C:\Program Files\nodejs\node.e

How do I access Vite configuration from code?

Inside vite.config.ts , I have: export default defineConfig({ base: '', plugins: [react()], server: { open: true, port: 3000, }, }); Is it possible to access these values, especially the port number, from code? Or perhaps it's better to set these through easily accessible environment variables instead? Via Active questions tagged javascript - Stack Overflow https://ift.tt/DV5wcv7

DiscordJS DiscordAPIError[50013]

I want to send a message to a channel here is my index.js const json = require('./jsonEdit.js'); const discordBot = require('./discordBot.js') const youtubeAPI = require('./youtubeAPI.js') const server = require('./httpServer.js') let intervalId = 0 let link = '' const main = async () => { var config = json.readJsonFile('./config.json'); try { result = await json.updateData('./config.json', await youtubeAPI.getChannelIDByUrl(config.YOUTUBE_CHANNEL_LINK)); config = result.config } catch (error) { console.error('Error updating config:', error); config = null } if(config == null) { return } await discordBot.start(json) await server.start(json) intervalId = setInterval(() => aprilFool(json), 1000); // Check every second, adjust as needed process(json) setInterval(() => process(json), config.INTERVAL); } main() async function process(json) { let res = await youtubeA

How to Share a Leaflet Map Instance Across Multiple Vue 2 Components?

Background: I'm building a web application using Vue 2 and Leaflet. I'm trying to share a single Leaflet map instance across multiple components in my application. Issue: I'm looking for a way to create a Leaflet map instance in one place and access and use it across multiple components in the entire application. Code Example: This is a method I have tried, but I don't know if this way of writing is appropriate. Maybe there is a better way: App.vue provide() { return { parent: this }; }, mounted() { this.map = L.map('map',{}) } components inject: ["parent"] Is there a more appropriate way? Via Active questions tagged javascript - Stack Overflow https://ift.tt/aVhrA5x

csv to html table ( header mapping | django)

I'm currently working on a Django project where users can upload a CSV file with headers in different languages. My goal is to allow users to map these headers to the corresponding fields in my database model. For example : Fields in the database: (first name, last name, age, country) User CSV header : (pays, prenom, nom, age) In this scenario, the user has provided all the necessary fields but in French and in a different order. After the user clicks the upload button, my plan is to load the CSV file into a table or another format that allows them to easily map the fields in the CSV file to the columns in my database. Thank you in advance. Tried using Pandas, but it just shows the CSV file as a table. No idea how to make the table header editable. Via Active questions tagged javascript - Stack Overflow https://ift.tt/JzPBnYy

onClick(props.function()) Causes Function Calls repetedly [duplicate]

I am trying to display different things depending if a element is clicked or not in a navbar, in body.main App.js content: const [showCatContent, setShowCatContent] = useState(false); const toggleCatContent = () => { setShowCatContent(!showCatContent); }; console.log(showCatContent) return ( <html><head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script defer src="theme.js"></script> <link rel="stylesheet" href="style.css" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700&display=swap" rel="stylesheet" /> </head> <body> <Navbar toggleCatContent={toggleCatContent} /> <body> <Navbar toggleCatContent={toggleCatContent} /> <main> {showCatContent ? ( <p>This is my cat ahahhahahah

How to check if each values in array exist in database

Simply, I am working on a project and I faced a case and want to know if I am implementing it correctly. I expect the client to send an array of IDs, and I need to check if each value in the array exists or not in the database. If any value does not exist, I will send a response with an error. Otherwise, I will proceed with the next actions. I have implemented the idea in the following way: let result = null; for (let i = 0; i < listIds.length; i++) { const existCheck = await branchModel.exists({ _id: listIds[i] }) != null ? true : false; if (existCheck == false) { result = false; } } if (result != false) { result = true; } return result; } However, I think this approach may impact performance if the array is very long, and I am not sure if calling the database multiple times in the same API is healthy and not expensive. Is there a method in Mongoose to achieve the same idea? Soluation : let result = false; let unique = [...new Set(listIds)]; co

Electron Squirrel Auto Updater The remote server returned an error: (308) Permanent Redirect

I was trying to make an auto-updater for my electron app and used Hazel as the update server, but when I tried this and tested it, following every step on the electron guide , It would always give me these errors in the Squirrel-CheckForUpdate.log file: [10/12/23 11:54:19] info: FileDownloader: Downloading url: https://cbsh-updater.vercel.app//update/win32/1.0.2/releases?id=bellschedoverlay&localversion=1.0.2&arch=amd64 [10/12/23 11:54:19] warn: IEnableLogger: Failed to download url: https://cbsh-updater.vercel.app//update/win32/1.0.2/releases?id=bellschedoverlay&localversion=1.0.2&arch=amd64: System.Net.WebException: The remote server returned an error: (308) Permanent Redirect. [10/12/23 11:54:19] info: CheckForUpdateImpl: Download resulted in WebException (returning blank release list): System.Net.WebException: The remote server returned an error: (308) Permanent Redirect. [10/12/23 11:54:19] fatal: Finished with unhandled exception: System.AggregateException: O