Does React rendering effects the setTimeout or setInterval function wrapped in a useRef and useRef is good way to achieve pause, stop, update question

I’m trying to achive the slider functionality, where I want to slider to move to the next question after every three seconds [this part is working fine]

Features i’m trying to achive:

OnMouseEnter: Timer stops, css aniamtion stops(working)
OnMoveleav: Start the timer from remaning time left
OnClick: Change Question number to the selected items (working) and start aniamtion

The issue is when I changed the question_number by onClick event, the next question start showing after every 1 seconds instead of 3 seconds. I think the problem is somehow with the React Re-redendring.

setSlider is simple useState has object:

`

const [ timeSlider, settimeSlider ] = useState({
    question_lenght: 4,
    question_number: 0,
    current_time: 0
  });

`

I’m using useEffect to check the viewport width so react Re-render the components everytime, Viewport changes

I tried to store the Interval for timmer in a react useRef. but still not working. Here is my code:

I use useRef, so I can Resume, Pause and updateNumber outSide where the first time setInterval started
const interval = useRef(null);

After EverySecond update the useState: Seconds

`

useEffect(() => {
    setRemaining({  start_time: Date.now(), stop_time: 0 });
    interval.current = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);
    pauseSlider();
    return () => clearInterval(interval);
  }, []);

`
And when ever the seconds state changed, I make sure after every three seconds. question_number increased only when its less than 3

`

useEffect(() => {
    if (seconds === 3) {
      setSeconds( seconds => 0 );
      settimeSlider( prev => prev.question_number === 3 ? { ...timeSlider, question_number: 0 } : { ...timeSlider, question_number: timeSlider.question_number + 1 } );
    }
  }, [seconds]);

`

Below are the pause, resume and udpate function.

`

function pauseSlider(){
    setSliderHover(true)
    setRemaining({  start_time: 0, stop_time: Date.now() });
    clearInterval(interval.current);
  }
  function resumeSlider(){
    setSliderHover(false)
    setRemaining( prev => ({ ...prev, start_time: prev.stop_time, stop_time: 0 } ));
    interval.current = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }
    , 1000);
  }
  function updateNumber(num){
    setSliderHover(false)
    setSeconds(0)
    setRemaining({  start_time: 0 , stop_time: 0 });
    clearInterval(interval.current);
    interval.current = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }
    , 1000);
    settimeSlider( { ...timeSlider, question_number: num } );
  }

`

The Problem could be in these functions, I tried to use setTimeout instead of setInterval same results.

Below is the picture of slider, so you have more clear idea what i’m trying to achive.

Demo of what i'm trying to achive, the current question_number is 3 (questions starts from 0)

I wanna deploy a telegram bot url

i wanna know how to deploy my app. I tried but I got it deployed but I don’t know how to link my telegram not url with firebase hosting.

Look at that now someone helped me deploy a project and after setting it up he requested for my telegram bot url to make it that way. Now I can put my company domain in the telegram bot, and then the firebase domain will redirect to my company domain

How to use variable inside useEffect in Reactjs

I am working with Reactjs and i am using Nextjs,Right now i am trying to get value of “Editor”,I want to know that
How can i get “variable value” inside “handleSubmit function” ? In other words how can i alert Editor values inside handleSubmit button ?
Here is my current code,Thank you in advance.

const [editor, setEditor] = useState()

useEffect(() => {
 if(editor){
   const content = editor.getContent();
   console.log('content is ' + content); //How can i pass "content to handlesubmit"
 }
}, [editor])

const handleSubmit = async(e: any) => {
        e.preventDefault();
        alert('content is ' + content);
         <Editor
            onInit={(evt, ed) => {
                setEditor(ed);
               }}
            initialValue="<p>This is the initial content of the editor.</p>"
            init={{
              height: 500,
              menubar: false,
              plugins: [
                'advlist autolink lists link image charmap print preview anchor',
                'searchreplace visualblocks code fullscreen',
                'insertdatetime media table paste code help wordcount'
              ],
              toolbar: 'undo redo | formatselect | ' +
              'bold italic backcolor | alignleft aligncenter ' +
              'alignright alignjustify | bullist numlist outdent indent | ' +
              'removeformat | help',
              content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
            }}
      />
 
};

How to convert array into object with out zeroth position [duplicate]

I’m trying to convert an array into an object

"loanArray" : [
   {
    "recordID" : "LKOCH123",
    "date" : "20221206",
    "productId" : "21023"
   }
]

I’ve converted this in to Object using Object.assign like below:

let loanObj= Object.assign({}, loanArray)
"loanObj" : {
   "0": {
    "recordID" : "LKOCH123",
    "date" : "20221206",
    "productId" : "21023"
   }
}

However I want to remove that “0” position in my object and the expected is below:
please help to achieve this structure.

"loanObj" : {
    "recordID" : "LKOCH123",
    "date" : "20221206",
    "productId" : "21023"
}

I am working on comparing and subtracting values from multiple Arrays

I’m working on a project where I have multiple variables, usually 3 to 6, and each variable has 2 values (placed in an array). I need to compare and subtract value 1 of Variable X to value 2 of Variable Y, and value 1 of Variable Y to value 2 of Variable Z and so on.

How would I accomplish this? (Bonus points if you tell me how to modify the numbers in the arrays before comparing them. How do you modify only a single value in a string and not the whole string itself?)

Here are some examples of a few variables:

let p17 = ["2", "4"];

let p33 = [“3”, “3”];

let p64 = ["5", "6"];

let p28 = [“6”, “2”];

p17's 2 goes to p28's 2, equaling 0.
p33's 3 goes to p17's 4, equaling -1.
p64's 5 goes to p33's 3, equaling 2.
and p28's 6 goes to p64's 6, equaling 0.

Note: I have 136 variables in this project that need to follow this formula, variables being pulled randomly (but I can work the rng part out).

Google Chat rest API (2022)

I am new to google apis and was navigating around google chat api. I followed their steps in creating app and authenticating users. However, when I tried it on postman, I get an error:errorInPostman. Can somebody help me on getting tokens using service account in postman?. Thank you in advance!

I already tried to use the service account’s Client ID and put it on postman but I am having a redirect_uri mismatch error. Where can I put the redirect_uri on service accounts?

Leaflet only loads the first row of tiles in my map

I’m not able to get Leaflet to load the tiles of my map past the first row in this Vue 3 component. I’ve tried declaring the vertical size of its div several ways, as well as calling map.invalidateSize() when the component is mounted, but without any success.

<script setup lang="ts">
import { onMounted } from "vue";
import * as L from "leaflet";
import "leaflet/dist/leaflet.css";

onMounted(() => {
  var map = L.map("map", { attributionControl: false }).setView([0, 0], 0);
  L.tileLayer("http://127.0.0.1:7800/{z}/{x}/{y}.jpeg", {
    maxZoom: 0,
    noWrap: true,
  }).addTo(map);
});
</script>

<template>
  <h1>Map Detail</h1>
  <div id="map"></div>
</template>

<style>
#map {
  width: 100%;
  height: 512px;
}
</style>

problem with loading css and javascript after get request

I was using express and the render function to load different pages of my website. However, I have decided to just go with vanilla js instead. The goal is to load the html file and all the js/css stuff too. Here is my code:

server:

const http = require('http');
const fs = require('fs');
http.createServer((req,res) => {

    res.writeHead(200, {'Content-type': 'text/html'})
    fs.readFile('./index.html', null, (err, data) => {
        if(err){
            res.writeHead(404);
            res.write('File not found')
        }else{
            res.write(data)
        }
        res.end();
    })

}).listen(3000);

html file:

<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="./styles/main.css">
      <script src="./src/global.js" defer></script>
      <title>Test</title>
  </head>
  <body>
      <div id="scene-lobby" class="scene">
        hello this is a test
      </div>
      <button id="button1">click me</button>
  </body>
</html>

when I load the webpage, the html file loads, but the css and javascript don’t. Also, I get this error regarding the javascript file:

Uncaught SyntaxError: Unexpected token ‘<‘ (at global.js:1:1)

Does anyone know how to fix this?

mapping an array of strings to an array of numbers based on key value pairs of another object

I am trying to map an array of strings

arrString = [
      ["A", "B"],
      ["C", "D"],
      ["E", "F"],
      ["D", "A"],
      ["F", "C"],
      ["G", "E"]
    ] 

based on an object of key values:

map =  {
  '0': 'A',
  '1': 'B',
  '2': 'C',
  '3': 'D',
  '4': 'E',
  '5': 'F',
  '6': 'G'
}

into an array of numbers

arrNum = [
      ["0", "1"],
      ["2", "3"],
      ["4", "5"],
      ["3", "0"],
      ["5", "2"],
      ["6", "4"]
    ] 

This is what I have done:

    const map = {}
    const arrNum = Array.from(new Array(arrString.length), () => new Array(arrString[0].length).fill([]));
    for(let i = 0; i < arr2.length; i++){
        map[i] = arr2[i]
    }
    for(let ele in arrString){
    // I can't figure out how to if the obbject value is equal to ele push it's key to arrNum
        if (Object.values(map).includes(ele)) 
    }

As you can see I am trying to loop through arrString and then if any element equals a value in map I want to add its key to arrNum.

So anyone knows how to do it so I can end up with arrNum?

how do i make a palindrome checker using “prompt” and “alert” boxes [duplicate]

I’m doing this for some kind of school work thing, it said that ill need to do a palindrome checker but all the other things I’ve searched seem to use a different method.

I tried using


var what = prompt("i am asking for a word");
console.log(what)

for (var i = what.length - 1; i >= 0; i--) {
    console.log(what[i])

after that I’m pretty much lost. I wanna know what I can do and use after that.

Javascript Mouseevent On Hover

Currently I am looking for some help with my mouse over event.

<div class="video-container">
<video id="my_video" loop muted poster="IMAGE_URL"> <!-- put your image here -->
  <source src="VIDEO_URL" type="video/mp4"> <!-- path to your video here -->
</video>
</div>

Above is my video-container, on my index page I am displaying 10 videos. Each of them should show a preview of the video when being hovered, however with my current javascript only the first video with my_video id is displaying the video preview when hovering.

let myVideo = document.getElementById("my_video");
myVideo.addEventListener("mouseover", () => {
    myVideo.play()
    image.style.display = 'none'
});

myVideo.addEventListener("mouseleave", () => {
    myVideo.pause();
});

How can I make it so that all videos on my homepage, behave in the same manner?

js concatenate text and variables quotes and doble quotes

u have few experience in javascript and have this situation new for me… i have an array made in php and pass it to js by JSON… no problem until here but now.. my problem.. i find a js function that make organizational charts but i need fill the name from a mysql data table.. how do this in js… here my code:

$sql_lared="SELECT * FROM reeco_reuse WHERE tipo_reuse='Red' and identif_red='$xidentif_red' and nivel> $xunivel ORDER BY reeco_reuse.nivel ASC";
$result_lared = mysqli_query($con, $sql_lared) or die(mysqli_error($con));
while ($row_lared = mysqli_fetch_assoc($result_lared)) {
  $reeco_red[$colu][0]=$row_lared['id'];
  $reeco_red[$colu][1]=$row_lared['id_padre'];
  $reeco_red[$colu][2]=$row_lared['avatar'];
  $reeco_red[$colu][3]=$row_lared['cdn'];
  $colu++;
}
?>
    <script>
        google.charts.load('current', {packages:["orgchart"]});
      google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        var passedArray = <?php echo json_encode($reeco_net); ?>;
        var jid =(passedArray[1][0]);
        var jpa =(passedArray[1][1]);
        var jav =(passedArray[1][2]);
        var jcd =(passedArray[1][3]);
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('string', 'Manager');
        data.addColumn('string', 'ToolTip');
                    
        data.addRows([
        [{'v':'Tim', 'f':'Tim <a href="hhh.com?thx=1"><button type="button" style="border:none;"><img class="table-avatar circular-square_v" src="../img/avatar/avatar4.png" width="40px" height="40px"></button></a>'},'', 'toolTip'],

in this and all cases i need replace Tim with jpa variable thx=1 the 1 with jid and avatr with jav

    [{'v':'Louis', 'f':'Louis <a href="hhh.com?thx=2"><button type="button" style="border:none;"><img class="table-avatar circular-square_v" src="../img/avatar/avatar6.png" width="40px" height="40px"></button></a>'}, 'Tim', 'VP'],


[{'v':'Peter', 'f':'Peter J.<div style="color:red; font-style:italic"></div>'},'Tim', 'VP'],
[{'v':'u-red1', 'f':'ured 40<div style="color:red; font-tyle:italic">unconfrmed</div>'},'Tim', 'VP'],

[{'v':'u-red2', 'f':'ured 42<div style="color:red; font-style:italic">unconfrmed</div>'},'Tim', 'VP'],
                              
[{'v':'Felix', 'f':'Felix02<div style="color:red; font-style:italic">Sales</div>'},'Louis', 'Salesman'],
                                                                  
['Alex', 'Louis', 'Bruce Wayne'],
['u-red3', 'Felix', 'Local Boy'],



]);
                    
                            // Create the chart.
                            var chart = new 
google.visualization.OrgChart(document.getElementById('chart_div'));
                            // Draw the chart, setting the allowHtml option to true for the tooltips.
                            chart.draw(data, {'allowHtml':true});
                          }
                    </script>