Radio Button Background Not Changing on First Click in React Component

I’m working on a React form where I’m trying to change the background color of a label when a radio button is selected, but when I click/check the button it first update the state and on second click it shows me the background color.

I’m using a combination of onChange and checked attributes to manage the radio button state.

I have go through the Chat-GPT but it is still not answering me correctly

Below is the code for the Task component and CSS.

import React, { useState } from 'react';

export default function Task() {
  let [formData, setformData] = useState({
    uName: '', 
    uGender: '', 
    uMedals: 0, 
  });

  let handleForm = (e) => {
    let { name, value } = e.target;
    if (name === 'uMedals') {
      value = parseInt(value);
      if (value <= 0){ 
          value = 0;
      if (value > 20) 
          value = formData.uMedals;
    }
    setformData((formData) => ({
      ...formData,
      [name]: value,
    }));
    e.preventDefault();
  };

  return (
    <div className='parent-container'>
      <div className='content-wrapper'>
        <div className='left'>
          <form className='form-wrapper'>
            <div className='name-wrapper'>
              <label>Name</label>
              {/* Name input */}
            </div>
            <div className='toogle-wrapper'>
              <label className='lbl-gen'>Gender</label>
              <div className='wrapper'>
                <div className='custom-input'>
                  <input
                    type='radio'
                    id='female'
                    name='uGender'
                    value='female'
                    onChange={handleForm}
                    checked={formData.uGender === 'female'}
                  />
                  <label htmlFor='female'>Female</label>
                </div>
                <div className='custom-input'>
                  <input
                    type='radio'
                    id='male'
                    name='uGender'
                    value='male'
                    onChange={handleForm}
                    checked={formData.uGender === 'male'}
                  />
                  <label htmlFor='male'>Male</label>
                </div>
              </div>
            </div>
            <button style={{ width: '320px' }}>Add</button>
          </form>
        </div>
      </div>
    </div>
  );
}

The below is the CSS code of above Task component

.custom-input input[type=radio] {
    display: none;
}
.custom-input label {
    display: block;
    padding: 6px 8px;
    color: #fff;
    font-weight: bold;
    text-align: center;
    transition: all 0.4s ease;
    cursor: pointer;
    border-radius: 4px;
    background-color: #717762;
}
.custom-input input[type='radio']:checked + label {
    background-color: #f5f5f5; 
    color: #000;
}

js throws Illegal invocation while importing a package dynamically

next: 12.3.2
node: 20.11.1
react: 17.0.2

  useEffect(function () {
    loadAuthFill();
  }, []);
  const loadAuthFill = async () => {
    appovalRef.current = await import('@ctrip/corp-bizComp-authprocess/dist/static/authProcess.js');
  };

error

the package which was about to import exports a object like this:
enter image description here

  1. I tried to import the package with dynamic api, but it didn’t work out like I expected. I expect
    that the package returns a object with Init, Submit function in the object

How can I have access to the Authorization header inside a request interceptor in Axios?

I have this code

axiosInstance.interceptors.request.use(
    async config => {
        const headers = config.headers;
        console.log('headers' , headers);
        console.log('headers', headers.Authorization);

return config ;
});

the first log I can see the Authorization header in the object :

headers {
“Accept”: “application/json, text/plain, /“,
“Authorization”: “Bearer abc123”
}


but the second log, Authorization is undefined :

headers undefined


How can I have access to the Authorization header inside a request interceptors in Axios?

Button shows sometimes and sometimes not

I’m trying to track watch time of a video with using JavaScript. But the problem is sometimes the script works well and sometimes it doesn’t. I want to show a Next video button when the video is 90% watched by user, in ideal scenario the button shows up button sometimes it just doesn’t, How can I fix this issue ?

this is my html, I’m using bootstrap CDN along with html:

<head>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="cursor-pointer pt-4 d-flex justify-content-center align-items-center flex-column">
   <video class="w-50" poster="" id="plyr-video-player" playsinline controls>
      <source src="https://therapywebsite.s3.amazonaws.com/Binaural+Beats+Fast+5+min+meditation+Stress+Relief+%5Bxc3MacYfdbI%5D.mp4" type="video/mp4" />
   </video>
</div>
<div class="pt-4 d-flex justify-content-center align-items-center flex-column">
   <h5>Welcome to this session</h5>
   <button class=" d-none w-25 btn btn-primary me-3" id="next-video-btn">Next video</button>
</div>
</body>

& this is my script:

<script>
    document.addEventListener("DOMContentLoaded", (event) => {
      const video = document.getElementById("plyr-video-player");
      const nextVideoBtn = document.getElementById("next-video-btn");

      const videoId = 1;
      const postInterval = 10;

      let playedCount = 0;
      let lastPlayedTime = 0;
      let totalWatchedTime = 0;
      let actualWatchedTime = 0;
      let isTabActive = true;
      let skipDetected = false;
      let isVideoVisible = true;

      document.addEventListener("visibilitychange", () => {
        isTabActive = !document.hidden;
      });

      const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          isVideoVisible = entry.isIntersecting;
        });
      }, {threshold: 0.5});
      observer.observe(video);

      video.addEventListener("loadedmetadata", () => {
        const videoDuration = Math.floor(video.duration);
        const playedCountThreshold = Math.floor(videoDuration * 0.9);

        if (videoDuration){
          console.log("Metadata loaded")
        } else{
          console.log("Metadata isn't loaded yet!!")
        }

        const showVideoBtn = () =>{
          if (video.currentTime > playedCountThreshold) {
            if (nextVideoBtn.classList.contains("d-none")) {
              nextVideoBtn.classList.remove("d-none");
            }
          }
        };

        function autoPlay() {
          return video.play();
        }
        autoPlay().catch(error => {
          console.error("Autoplay failed:", error);
        });
        setTimeout(autoPlay, 1000)

        function trackVideo(eventType, currentTime){
          currentTime = Math.floor(currentTime);
          if (isTabActive && isVideoVisible){
            if (currentTime > playedCountThreshold && lastPlayedTime <= playedCountThreshold) {
              playedCount++;
            }
            if (eventType !== "play" || eventType === "timeupdate"){
              const timeDiff = Math.max(0, currentTime - lastPlayedTime);
              actualWatchedTime += timeDiff;
            } else if (eventType === "seeked") {
              skipDetected = true;
              const skippedTime = Math.max(0, currentTime - lastPlayedTime);
              actualWatchedTime -= skippedTime;
            }
            totalWatchedTime = actualWatchedTime;

            fetch("/track_video/", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "X-CSRFToken": "{{ csrf_token }}"
              },
              body: JSON.stringify({
                video_id: videoId,
                played_count: playedCount,
                video_duration: videoDuration,
                last_played_time: lastPlayedTime,
                total_watched_time: totalWatchedTime,
              })
            });
          }
          lastPlayedTime = currentTime;
        }

        video.addEventListener("play", () => trackVideo('play', video.currentTime));
        video.addEventListener("pause", () => trackVideo("pause", video.currentTime));
        video.addEventListener('timeupdate', () => {
          if (video.currentTime - lastPlayedTime >= postInterval) {
            trackVideo('timeupdate', video.currentTime);
          }
          showVideoBtn();
        });
        video.addEventListener("seeked", () =>{
          skipDetected = true;
          lastPlayedTime = Math.floor(video.currentTime)
          trackVideo("seeked", video.currentTime)
        });
      });
      nextVideoBtn.addEventListener("click", () => {
        window.location.href = "/next_video.html";
      });
    });
</script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>

trying to print to command line in puppeteer from within page.evaluate

I am very new to puppeteer. I have a puppeteer script (node v20.15.0) and I’m trying to write/print to the command line from inside a page.evaluate that’s inside an async function. I was following this example:

https://stackoverflow.com/a/61336937/1827764

If I run that code, it works perfectly. I can even modify it to pass a variable like this:

await page.exposeFunction("myFunc", (value) => console.log(value));
await page.evaluate(async () => {
    await myFunc('test');
       return true;
});

However, I have something like this:

const puppeteer = require('puppeteer');
const fs = require('fs'); //filesystem functions
const path = require('path'); //path-related functions
const https = require('https')

process.on('uncaughtException', function (exception) {
  console.log(exception); 
});

(async () => {
    var browser;

    var puppeteer_options = {
        headless: true, 
        ignoreHTTPSErrors: true, 
        args: ['--no-sandbox', '--disable-setuid-sandbox', '--single-process', '--no-zygote', '--disable-dev-shm-usage', '--shm-size=4gb', ], 
        defaultViewport: {width: 1920, height: 1080},
        protocolTimeout: 1000000, //https://www.puppeteersharp.com/api/PuppeteerSharp.LaunchOptions.html
    }

    browser = await puppeteer.launch(puppeteer_options);

    var page = await browser.newPage();
    
    await page.exposeFunction("logInNodeJs", (value) => console.log(value));

    var gp_args = {}
    gp_args['x_data'] = {}
    if(gp_args['x_data'])
    {
        var x = await get_x({x_data: gp_args['x_data'], gp_args:gp_args})
    }

    async function get_x(options)
    {
        var url = '<url>'

        await page.setDefaultNavigationTimeout(0)

        await page.goto(url, {waitUntil: 'networkidle2'});

        gp_args['waitforselector'] = "div[class='paging']"
        gp_args['waitforselector_timeout'] = 30000

        try
        {

            await page.waitForSelector(gp_args['waitforselector'], {visible: true, timeout: gp_args['waitforselector_timeout'] })

        }
        catch(err)
        {
            console.log(err)
            return
        }
    
        var el = await page.evaluate(async () => {
            await logInNodeJs('test 1')
        
            var el = document.querySelector("div[class='paging']")
        
            pages = el.querySelectorAll('a')
            return pages.length - 1
        })
        
        console.log(el)
    }
})()

In this example, when the “await logInNodeJs(‘test 1’)” runs, the only output I get is:

[

just a left bracket. I don’t know why it isn’t printing out ‘test 1’, and I don’t know where the “[” is coming from.

javascript XSS flaw

can somebody help fixing flaw on line “11” i believe its the “id” since the html already sanitized, Veracode complaining about it.

$(document).ready(function () {
    function populateSelect(id, parentId) {
      var html = '';
      $.getJSON('list.json', function (data) {
        html += `<option value="">Select ${DOMPurify.sanitize(id)}</option>`;
        $.each(data, function (key, value) {
          if ((id === 'App' && value.parent_id === '0') || (id !== 'App' && value.parent_id === parentId)) {
            html += `<option value="${DOMPurify.sanitize(value.id)}">${DOMPurify.sanitize(value.name)}</option>`;
          }
        });
        $(`#${id}`).html(html);
      });
    }
  
    populateSelect('App');
  
    $('#App').on('change', function () {
      var appId = $(this).val();
      if (appId) {
        populateSelect('Source', appId);
      } else {
        $('#source').html('<option value="">Select Source</option>');
      }
    });
  });

How do I make it so when my money is at a certain value, a button appears

I tried and tried and don’t understand. I’m new to this, I learn by people doing it for me (I know… it’s weird, but I study what they do, make sure I understand completely, and then implement it into my code and other projects). But y’all do not have to do it for me, though would be greatly appreciated. I need it so when my money reaches 200 a button appears.

Here’s the fiddle
jsfiddle.net/Weston1256/e5j4p8uw/81/embed/

I tried

function firstItemFunction() {
var num = document.getElementById(“score”);
num.firstItem(1);
store.set(‘putAKeyHere’, num.value);
if (num.value >= 200)
}

Which didn’t seem to work but it would be appreciated as I have to make a game for school that represents capitalism) any help is greatly appreciated!

Twilio serverless function async operations execute order problem

What I’m trying to do:

  1. Incoming call from user would trigger a Digits Gather (No problem)
  2. After receiving the Digits, Say something to the user
  3. Play music while fetching phone number from an API using async/await
  4. Dial said phone number from API’s response.

My Code:

gather-extension.js (Gather and retry both work, thus not providing retry js)

exports.handler = async (context, event, callback) => {
  const retryMax = 2;
  const twiml = new Twilio.twiml.VoiceResponse();

  const gather = twiml.gather({
    action: `./fetch-driver-phone`,
    method: 'GET',
    timeout: 2
  });

  gather.say('Thanks for calling');
  //retry
  twiml.redirect(`./retry-gather-ext?retry=1&retry_max=${retryMax}`);

  return callback(null, twiml);
}

fetch-driver-phone.js (This is where the problem is)

exports.handler = async (context, event, callback) => {
  const twiml = new Twilio.twiml.VoiceResponse();

  const callerPhoneNumber = event.From;
  const extension = event.Digits;

  console.log('Caller Phone Number:', callerPhoneNumber);

  if (extension == null) {
    //handle error
  }

  twiml.say("Please wait while we connect you");
  twiml.play("http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3");

  try {
    console.log("Calling API");
    const result = await fetchDriver(extension, twiml)
    console.log(result);

    twiml.dial().number(result);
    callback(null, twiml);
  } catch(error) {
    console.error(error);
    twiml.say('We are unable to process your request at this time.');
    twiml.hangup();
    callback(error);
  }
}

const fetchDriver = async (code) => {
  console.log('Extension Digits:', code);
  return new Promise((resolve) => {
    setTimeout(() => {
        resolve('phone number');
    }, 5000);
  });
}

What is expected:

I expect the Say and Play to execute before the await statement. Then Dial is called after the response is fetched.

What is happening:

Say and Play are not triggered UNTIL await’s 5000ms is over, then Dial is flat-out ignored. I have tried using the actual API, and I got the same result.

When I use chatGPT or Twilio support AI. Both Gave me the solution of adding callback(null, twmil) right after Play. This indeed fixed the timing issue, however, it resulted in Dial never being called.

Then both AI’s suggested adding an additional VoiceResponse to be used after the first callback(null, twmil). This results in the response console.log showing up at the beginning of the 2nd call. The first call would still be stuck in the Play music.

I also tried using Enqueue, but got the same result.

I ran out of options and things to try. Thus I’m seeking help here. Thanks for any input!

How to achieve both exact timestamps and pitch preservation when changing playback speed in web audio?

I’m working on a web app where I need to load audio with two key requirements:

1.  Exact timestamp alignment: I need precise control over timestamps for synchronization and tracking purposes.
2.  Pitch preservation when changing playback speed: When adjusting the playback speed, I want the pitch to stay the same as the original.

I’ve found that the Web Audio API provides precise timestamps, but the HTML5 element preserves pitch when the speed changes.

Is there any way to combine the advantages of both approaches? I need to ensure the audio sounds natural when speeding up or slowing down, while still maintaining exact timestamps.

Any guidance or suggestions would be greatly appreciated!

I’ve tried using Howler.js and WaveSurfer.js for this, but I’ve encountered the same limitations in both. If I load using HTML 5 it acts like HTML5 Audio element, and the same is true if load it as WebAudio Api.

What are the best practices for structuring a large JavaScript project?

I’m working on a large JavaScript project and want to ensure that it’s well-structured and maintainable. I’ve read that project organization can significantly impact development efficiency and scalability.

What are some best practices or recommended patterns for structuring a large JavaScript application? I’m interested in advice on folder structure, modularization, and managing dependencies.

In React.js I keep getting an error in regard to a component being controlled to being uncontrolled, how can I fix this?

I am trying to recreate a simple pokedex app in react that I made in vanilla javascript. I’m trying to get more API practice, but keep running into this error in the console: “Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.”

I tried making my states an empty array and then tried an empty object, but I am still getting the same error message. Any help would be appreciated.

This is the code I have written so far:

import { useState, useEffect } from "react";
import PokemonDetails from "./PokemonDetails";
import Paper from "@mui/material/Paper";
import InputBase from "@mui/material/InputBase";
import IconButton from "@mui/material/IconButton";
import SearchIcon from "@mui/icons-material/Search";
export default function PokemonData() {
  const [searchInput, setSearchInput] = useState("");
  const [pokemonData1, setPokemonData1] = useState(null);
  const [pokemonData2, setPokemonData2] = useState(null);

  useEffect(() => {
    const fetchData1 = () =>
      fetch(
        `https://pokeapi.co/api/v2/pokemon/${searchInput.toLowerCase()}`
      ).then((response) => response.json());
    const fetchData2 = () =>
      fetch(
        `https://pokeapi.co/api/v2/pokemon-species/${searchInput.toLowerCase()}`
      ).then((response) => response.json());

    // Using Promise.all to wait for both requests to complete
    Promise.all([fetchData1(), fetchData2()])
      .then(([result1, result2]) => {
        setPokemonData1(result1);
        setPokemonData2(result2);
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  }, []);

  //   SEARCH POKEMON
  const onSearch = (e) => {
    e.preventDefault();
    setSearchInput(e.target.value);
  };

  return (
    <div>
      <Paper
        component="form"
        onSubmit={onSearch}
        sx={{ p: "2px 4px", display: "flex", alignItems: "center", width: 400 }}
      >
        <InputBase
          sx={{ ml: 1, flex: 1 }}
          placeholder="Search Pokémon"
          inputProps={{ "aria-label": "search pokémon" }}
          value={searchInput}
          onChange={onSearch}
        />
        <IconButton
          type="button"
          onClick={onSearch}
          sx={{ p: "10px" }}
          aria-label="search"
        >
          <SearchIcon />
        </IconButton>
      </Paper>
      {/* <PokemonDetails pokemon={pokemonData1} /> */}

      <h1>Pokemon data from Endpoint 1:</h1>
      <pre>{JSON.stringify(pokemonData1, null, 2)}</pre>

      <h1>Pokemon data from Endpoint 2:</h1>
      <pre>{JSON.stringify(pokemonData2, null, 2)}</pre>
    </div>
  );
}```

Detecting if there an element or iframe overlaid on top of my iframe to prevent clickjacking

Detecting if there an element or iframe overlaid on top of my iframe

I have an iframe that can be embedded inside any website based on the content security policy.

Is there a way for the my iframe code to detect if there is an element or iframe laid on top of it to prevent clickjacking?

I tried using the trackVisibility in the IntersectionObserver v2 API for this purpose. Let us assume for now that we are good with the fact that support on Chrome is good enough.

For simplicity of discussion, let us assume that the threshold is set to 1.0, so that the entire iframe has to be visible for isVisible to be true. Also, let us call my iframe as iframeGood and the overlaid malicious iframe to be iframeBad.

If the opacity of iframeBad is set to anything higher than 0, then the isVisible of the IntersectionObserver API shows the value as false.

However, if the opacity of the iframeBad is set to 0, then the isVisible of the IntersectionObserver API shows the value as true. Maybe this is intended since iframeGood is fully visible in this case, but it does not solve of the problem of clickjacking.

So is there a way to detecting if there an element or iframe overlaid on top of my iframe from within my iframe?

javascript function return undefined while the variable is set [duplicate]

i have no idea why this code return undefined
i set success variable so if request is success its true otherwise its false

function deleteorder(url, pk) {
    let success
    $.ajax
        (
            {
                type: "GET",
                url: url,

                success: function (data) {
                    console.log("object deleted")
                    success = true
                },
                error: function (data) {
                    console.log(data)
                    success = false
                }
            }
        )
    return success
}

but when i run the function below its log undefined on console

function deletefromcart(url,pk){
    let status;
    status = deleteorder(url,pk)
    console.log(status)
    if(status==true){
        $("#cart"+pk).remove()
        $("#row"+pk).remove()
        if($("tbody > tr").length==0){
            setTimeout(() => {
                location.reload()
            }, 500);
            
        }
    }

}

browser image

so any idea why this happened?

building the value attribute of an option tag using jQuery

I have a function like this where I’m dynamically generating the option tag of a select.

function colorInfo(data) {
    console.log("Color Info");
    console.log(data);
    let colorData = JSON.parse(data);

    console.log(colorData);

    $.each(colorData, function (key, value) {
        $("#lineupColors").append(
        $("<option></option>")
           .attr("value",'{"colorId":'+value.colorId+',"colorCode":'+value.colorCode+'}')
          .text(value.colorName)
      );
    });
  }

Since I am defining the value as a Json object, how can I add double quotes such that the value would look like {"colorId":"1","colorCode":"#FFFFFF"}.

Right now it is coming out like this – which is not a valid JSON :

{"colorId":1,"colorCode":#FFFFFF}.

Webpack: Module not found: Error: Can’t resolve

I am trying to package my first vscode extension that I have tested under debugger.

In package.json, in scripts list, I have added the line

"package": "webpack --mode production --devtool hidden-source-map"

I used the recommended webpack.config.js file with minimal modifications (entry: the top JS file, extensions: I added ‘.js’). I have NOT changed the module part that I don’t understand the role and which is not explained in the tuto.

I succeeded to invoke the webpack command under vscode.
All sources have correctly built.
But then I get error for all required node.js modules (my own sub-modules seem to be correctly found).
The errors say:

Module not found: Error: Can't resolve '<the node.js module name>' in '<source directory>'

The line pointed by the error reads:

const <the node.js module name> = require('<the node.js module name>');

Lot of people have similar errors but not in same context so I found no solution that I feel applicable in my case.