react function not using updated state

My handlekeyup function is not using any of the new values in the state. In the function, playingTrackInd is always equal to -1, even when the state has been updated for playingTrackInd to be something else.

import React, { useEffect, useRef, useState } from 'react';
import { Container, Form, } from 'react-bootstrap';
import useAuth from './useAuth';
import SpotifyWebApi from "spotify-web-api-node";

const spotifyApi = new SpotifyWebApi({
    clientId: "Client Id"
});


interface DashboardProps {
    code: string,
}

export interface Track {
    artist: string,
    title: string,
    uri: string,
    albumUrl: string,
    previewUrl?: string,
}
export default function Dashboard({ code }: DashboardProps) {
    const accessToken = useAuth(code);
    const [playingTrackInd, setPlayingTrackInd] = useState<number>(-1);
    const tracks = useRef<Array<Track>>([]);
   
    // add keylistener
    useEffect(() => {
        document.addEventListener('keyup', handleKeyUp);

    }, []);


    // this function always has playingTrackInd as -1, even when the state has been updated by setPlayingTrackInd
    function handleKeyUp(e: any) {
        if (e.keyCode === 39) {
            // right arrow pressed
            if (playingTrackInd === tracks.current.length - 1) {
                getRandomTrack(() => setPlayingTrackInd(prevInd => prevInd + 1));
            }
            else {
                setPlayingTrackInd(prevInd => prevInd + 1)

            }

        }
        else if (e.keyCode === 37) { // left arrrow key pressed

            if (playingTrackInd > 0) {
                setPlayingTrackInd(prevInd => prevInd - 1);

            }
        }
    }

    // function that gets random track and adds it to tracks
    function getRandomTrack(callback?: Function) {

        getRandomTrackFromApi().then((track) => {
            tracks.current.push(track);
            if (callback) {
                callback();

            }

        })
    }

    // get first random track and set playingTrackInd to 0. This happens as soon as the component is loaded
    useEffect(() => {
        if (!accessToken) return;
        spotifyApi.setAccessToken(accessToken);

        if (playingTrackInd === -1) { 
            getRandomTrack(() => setPlayingTrackInd(0));
        }
        getRandomTrack();
        getRandomTrack();


        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [accessToken]);

    return (
        (component that depends on tracks[playingTrackInd])
    );
}

I can’t understand why playingTrackInd is always -1 only in the handleKeyUp function. Everywhere else, including the return statement, it is the proper value. Thanks.

why doesnt i get the variable?

im trying to let a variable from JSON and use it in other function but I’m doing something wrong can someone help me?
the code is`

async function githubUsers() {
  let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d')
  let shipsJSON =  await response.json()
}

githubUsers()



shipsJSON.forEach((item) => {
  item.forEach((nestedItem) => {
    placeCharacter(nestedItem.x, nestedItem.y, "O", myGrid)
    // placeCharacter(nestedItem.x, nestedItem.y, 'O', myGrid);
    placeRandomCharacter('O', enemyGrid, enemyGridSize);
    drawBreak();

  })

specifying a condition when sending payload axios and mongoose

Accounts model:

let accountsSchema = new mongoose.Schema({
    posts:{
        type: Array
    }
});

const Post = mongoose.model("Account", postSchema);

postController in Posts Microservice:

 let myAccountPosts = await axios.get(`${process.env.ACCOUNTS_MICROSERVICE_URL}/router/account/${userID}`)
.then((resp) => {
    
    resp.data.message.map((account) =>{

        
        account.posts.map((post) =>{
            

            if(myUserPostID !== post._id){
                
                                    
                
        //the following resets the entire posts array in the other microservice, consider resetting/deleting only that particular post
                let deletePostFromAccountsMicroservice = axios.patch(`${process.env.ACCOUNTS_MICROSERVICE_URL}/router/account/update/${userID}`, {"posts.$[]": "abc"}, (err) =>{
                    if(err) return err;
                });


            }else{
                console.log("no")

            }

        });
        
    });
}).catch((err) =>{
    console.log("err: ", err.message);
    return err;
});

This is how the response looks like:

{

  posts:[{_id:'6290ed85716a08d29dab3aa5'}, { _id: '1234ed85716a08d29b35342' } ]
  
}  
  
  
  

In the following line of code:

        let deletePostFromAccountsMicroservice = axios.patch(`${process.env.ACCOUNTS_MICROSERVICE_URL}/router/account/update/${userID}`, {"posts.$[]": "abc"}, (err) =>{
                    if(err) return err;
                });

I want the posts.$[] to target only the
object that has an _id that matches this condition (myUserPostID !== post._id).

How to achieve that?

Why is gatewayAdapt=4itemAdapt attached to url in one system not in another?

I have written a chrome extension, where a wordpress plugin generates a link:
{someOnlineStore.com}/{item-1}.html?{passing a few parameters}

the chrome extension reads the parameter and acts accordingly. What I am trying to figure out why any of my systems do not attach “&gatewayAdapt=4itemAdapt” to the end but on my client it does. Without including “gatewayAdapt=4itemAdapt”, there are five other pairs. And the url is pretty long.

The link when copied from wordpress site doesn’t contain gatewayAdapt=4itemAdapt but once it goes there, gatewayAdapt=4itemAdapt is attached at the end.

Thanks a lot.

Rotating an object with spherifical coordinates Three js

Im trying to roatate this space ship that i created, the rotation itself works the problem is that whenever i rotate it with the left and right arrow keys i want the spaceship to rotate just like with cartesian coordinates the problem is that whenever the objects rotates around the planet, the spaceship inclination doesnt change at all, like it would with cartesian coordinates and i dont get why really because the rotation around the planet itself works.

Sorry if the code is too long most of it is just to create the spaceship itself, i think the problem itself is in the update function itself.

Program:

/*global THREE*/
var camera = [];
var scene, renderer, currentCamera = 0;

var viewSize = 40;
var aspectRatio;

var geometry, material, mesh;
var wiredObjects = [];

var leftArrow, rightArrow, upArrow, downArrow;
var clock = new THREE.Clock();

//!!var controls;

var defaultScale = 1;
var planetRadius = 12;
var rocketHeight = planetRadius/12;
var rocketPartHeight = rocketHeight/2;
var rocketInfRadius = rocketPartHeight;
var rocketMidRadius = rocketPartHeight/2;
var rocketSupRadius = 0;
var boosterRadius = rocketInfRadius/5;
var boosterHeight = rocketInfRadius/4;
var rocketTrashDistance = 1.2 * planetRadius;
var objPositions = [];
var objAngles = [];
var nrTrash = 20;
var floatingTrash = [];
var trashSizes = [];
var minTrashSize = planetRadius/24;
var maxTrashSize = planetRadius/20;
var trashGeometries = [];

var copyVideo;
var universe;
var planet;
var rocket;
var loader = new THREE.TextureLoader();
var space_texture = new THREE.TextureLoader().load(
    "https://wallpaperaccess.com/full/1268183.jpg"
    );

'use strict';

function addObjPart(obj, geometry, mater, hex, x, y, z, rotX, rotY, rotZ) {

    material = (mater != null)? mater : new THREE.MeshBasicMaterial({color: hex, wireframe: wires});
    mesh = new THREE.Mesh(geometry, material);
    mesh.rotateX(rotX);
    mesh.rotateY(rotY);
    mesh.rotateZ(rotZ);
    mesh.position.set(x, y, z);
    obj.add(mesh);
    wiredObjects.push(mesh);
    return mesh;
}

function getObjPositions() {
    var i;
    var nrObj = nrTrash+1;
    var angleTheta, anglePhi;
    var objX, objY, objZ;
    var posVector = new THREE.Vector3(0,0,0); // spherical coordinates vector
    var angleVector = new THREE.Vector2(0,0); // angles Theta and Phi for spherical coordinates

    for (i = 0; i < nrObj; i++) {
        angleTheta = Math.random() * 2*Math.PI;
        anglePhi = Math.random() * 2*Math.PI;
        angleVector.set(angleTheta, anglePhi);
        objAngles.push(angleVector);

        objX = rocketTrashDistance * Math.sin(angleTheta) * Math.sin(anglePhi);
        objY = rocketTrashDistance * Math.cos(angleTheta);
        objZ = rocketTrashDistance * Math.sin(angleTheta) * Math.cos(anglePhi);
        posVector.set(objX, objY, objZ);    
        objPositions.push(posVector);
    }
}

function createUniverse(x, y, z, scale) {
    wires = true;
    universe = new THREE.Object3D();
    universe.scale.set(scale, scale, scale);
    var rocketPos = objPositions[0];

    addPlanet(universe, 0, 0, 0);
    addRocket(universe, rocketPos.x, rocketPos.y, rocketPos.z);
    addAux(universe);
    
    universe.position.set(x, y, z);
    scene.add(universe);
    return universe;
}

function addPlanet(obj, x, y, z) {
    planet = new THREE.Object3D();
    geometry = new THREE.SphereGeometry(planetRadius);
    
    var planetTexture = new THREE.TextureLoader().load(
        "https://st2.depositphotos.com/5171687/44380/i/450/depositphotos_443805316-stock-photo-equirectangular-map-clouds-storms-earth.jpg"
        );
    var planetMaterial = new THREE.MeshBasicMaterial( {
        map: planetTexture,
        transparent:true,
        side:THREE.DoubleSide,
        } );

    addObjPart(obj, geometry, planetMaterial, 0x0000ff, x, y, z, 0, 0, 0);
}

function addRocket(obj, x, y, z) {
    rocket = new THREE.Group();
    var n_rocket = new THREE.Object3D();
    addRocketTop(n_rocket, 0, 0, -rocketPartHeight/2);
    addRocketBottom(n_rocket, 0, 0, rocketPartHeight/2);
    addRocketBooster(n_rocket, 0, rocketInfRadius-boosterRadius, rocketPartHeight+0.5*boosterHeight);
    addRocketBooster(n_rocket, 0, -rocketInfRadius+boosterRadius,rocketPartHeight+0.5*boosterHeight);
    addRocketBooster(n_rocket, rocketInfRadius-boosterRadius, 0, rocketPartHeight+0.5*boosterHeight);
    addRocketBooster(n_rocket, -rocketInfRadius+boosterRadius, 0, rocketPartHeight+0.5*boosterHeight);
    rocket.add(n_rocket);
    rocket.position.set(x, y, z);
    obj.add(rocket);
    return rocket;
}

function addRocketTop(obj, x, y, z) {
    geometry = new THREE.CylinderGeometry(rocketMidRadius, rocketSupRadius, rocketPartHeight, 41,1);
    addObjPart(obj, geometry, null, 0xff0000, x, y, z, Math.PI/180*90, 0, 0);
}

function addRocketBottom(obj, x, y, z) {
    geometry = new THREE.CylinderGeometry(rocketInfRadius, rocketMidRadius, rocketPartHeight, 41,1);
    addObjPart(obj, geometry, null, 0x000fff, x, y, z, Math.PI/180*90, 0, 0);
}

function addRocketBooster(obj, x, y, z) {
    geometry = new THREE.CapsuleGeometry(boosterRadius, boosterHeight, 0.5, 20);
    addObjPart(obj, geometry, null, 0xff0000, x, y, z, Math.PI/180*90, 0, 0);
}

function addTrash(x, y, z) {

}


function render() {
    renderer.render(scene, camera[currentCamera]); // tells 3js renderer to draw scene visualization based on camera 
}

function onResize() {
    if (window.innerWidth > 0 &&  window.innerHeight > 0){
        var i;
        var val = 2;
        aspectRatio = window.innerWidth / window.innerHeight;
        renderer.setSize(window.innerWidth, window.innerHeight);
        var nrCameras = camera.length;
        for (i = 0; i < 1; i++) { // Ortographic Cameras
            camera[i].left = -viewSize * aspectRatio / val;
            camera[i].right = viewSize * aspectRatio / val;
            camera[i].top = viewSize / val;
            camera[i].bottom = viewSize / -val;
            camera[i].updateProjectionMatrix();
        }
        for (i=1; i < nrCameras; i++) { // Perspective cameras
            camera[i].aspect = aspectRatio;
            camera[i].updateProjectionMatrix();
        }
    }
}

function update()
{
    var timeOccurred = clock.getDelta();
    var rocketSpeed = Math.PI/180 * 40;

    if (rightArrow || leftArrow || upArrow || downArrow) { // rocket movement flags
        var rocketTheta = objAngles[0].x;
        var rocketPhi = objAngles[0].y; 
        var rocketX, rocketY, rocketZ;
        
        if (leftArrow){
            rocketPhi += rocketSpeed * timeOccurred;
        }
        if (rightArrow){
            //n_rocket.rotation.x += - rocketSpeed * timeOccurred;
            rocketPhi += - rocketSpeed * timeOccurred;
        }
        if (upArrow){
            //n_rocket.rotation.z += - rocketSpeed * timeOccurred;
            rocketTheta += -rocketSpeed * timeOccurred;
        }
        if (downArrow){
            //n_rocket.rotation.z += rocketSpeed * timeOccurred;
            rocketTheta += rocketSpeed * timeOccurred;
        }
        
        rocketX = rocketTrashDistance * Math.sin(rocketTheta) * Math.sin(rocketPhi);
        rocketY = rocketTrashDistance * Math.cos(rocketTheta);
        rocketZ = rocketTrashDistance * Math.sin(rocketTheta) * Math.cos(rocketPhi);
        
        rocket.position.set(rocketX, rocketY, rocketZ);
        
        objAngles[0].set(rocketTheta, rocketPhi);
        objPositions[0].set(rocketX, rocketY, rocketZ);
    }
}

function animate() {
    update();
    requestAnimationFrame(animate);
//  controls.update();
    render();
}

function addAux(obj) {
    geometry = new THREE.SphereGeometry(5);
    addObjPart(obj, geometry, null, 0xffc0cb, 15, 0, 0);
    addObjPart(obj, geometry, null, 0xffff00, 15, 0, 0);
    addObjPart(obj, geometry, null, 0x0000ff, 15, 0, 0);
}

function createScene() {
    scene = new THREE.Scene();
    scene.add(new THREE.AxesHelper(100));
    scene.background = space_texture;
    getObjPositions();
    universe = createUniverse(0, 0, 0, defaultScale);
}

function createOrtographicCamera(x, y, z) {

    var val = 2;
    aspectRatio = window.innerWidth / window.innerHeight;
    var camera = new THREE.OrthographicCamera( viewSize * aspectRatio/-val, 
                                                                                    viewSize * aspectRatio / val, 
                                                                                    viewSize / val, 
                                                                                    viewSize / -val, 
                                                                                    1, 
                                                                                    1000);
    camera.position.x = x;
    camera.position.y = y;
    camera.position.z = z;
    
    camera.lookAt(scene.position);
    
    return camera;
}

function onKeyDown(e) {
    var keyName = e.keyCode;
    switch (keyName) {
        case 49://1
            currentCamera = 0;
            break;  
        case 37 : // left arrow key
            leftArrow = true;
            break;
        case 38: // up arrow key
            upArrow = true;
            break;
        case 39: // right arrow key
            rightArrow = true;
            break;
        case 40: // down arrow key
            downArrow = true;
            break;
        default:
            break;
    }
}

function onKeyUp(e) {
    var keyName = e.keyCode;
    switch (keyName) {
        case 37 : // left arrow key
            leftArrow = false;
            break;
        case 38: // up arrow key
            upArrow = false;
            break;
        case 39: // right arrow key
            rightArrow = false;
            break;
        case 40: // down arrow key
            downArrow = false;
            break;
        default:
            break;
    }
}

function init() {
        
    renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    
    createScene();
    camera[0] = createOrtographicCamera(viewSize, 0, 0);
//!!    controls = new THREE.OrbitControls(camera[0], renderer.domElement);
    animate();
    window.addEventListener("resize", onResize);
    window.addEventListener("keydown", onKeyDown);
    window.addEventListener("keyup", onKeyUp);
}

Vuejs does not fetch hasOne relational data from laravel API

I am creating a vue component for Invoices to display them in a table. From the controller, I am sending 2 more tables (“customers” & “invoice_products”) related to invoices table in order to populate them. I am sharing the API (where it clearly returns them)

{
  "invoice": {
  "id": 13,
  "customer_id": "2",
  "gross_total": 65,
  "vat": 5,
  "tax": 10,
  "status": 1,
  "created_at": "2022-05-30T03:46:54.000000Z",
  "updated_at": "2022-05-30T03:46:54.000000Z",
  "invoice_products": {
      "id": 5,
      "invoice_id": 13,
      "product_id": 1,
      "quantity": 22,
      "total": 40,
      "updated_at": "2022-05-30T03:46:54.000000Z",
      "created_at": "2022-05-30T03:46:54.000000Z"
 },
"customers": {
    "id": 2,
    "name": "Customer B",
    "email": "[email protected]",
    "phone": "789456123",
    "address": "Dhaka",
    "created_at": null,
    "updated_at": null
 }
},

But when I try to fetch them like getInvoiceById.invoiceProducts.quantity, It returns the following error :

enter image description here

The tables look like :

enter image description here

enter image description here

From the model :

public function invoiceProducts() {
    return $this->hasOne('AppModelsInvoiceProduct', 'invoice_id');
}

public function customers() {
    return $this->belongsTo('AppModelsCustomer', 'customer_id');
}

From Controller :

public function singleInvoice(Request $request, $id) {
    $data['invoice'] = Invoice::with('invoiceProducts', 'customers')->where('id', $id)- 
     >first();
    return response()->json($data,200);
}

From template :

 <td>{{ invoiceInfo.customers.name }}</td>

From script :

export default {

    data() {
        return {
           allerrors : [],
           invoiceInfo : [],
       }
   },

   mounted() {
      axios.get('/api/single-invoice/'+this.$route.params.id).then(response => {
         this.invoiceInfo = response.data.invoice
      })
   }
}

Chrome: EvalError: Possible side-effect in debug

I’m trying to do some code in browser’s console, but I get this error on window.onerror event too.

Just load this simple page …

<script type="text/javascript">
        //error message
        window.onerror = function (msg, url, line, col, error) {
            console.log(error);
            if (confirm(error.name + ':' + error.message)) {
                location.reload(true);
                return true;
            }
        };
</script>
<div >
</div>

Only last file is uploading while selecting multiple files in React

I am using react with typescript. I am uploading multiple files on the endpoint. I am also uploading each file in multiple chunks. If I select a single file then it is uploaded without any issue but the problem occurs when I am choosing more than one file. The file on the nth index of the array is uploading only.

Here is my code:

const [progress, setProgress] = useState<number>(0);
  const [fileSize, setFileSize] = useState<number>(0);
  const [chunkCount, setChunkCount] = useState<number>(0);
  const [beginingOfTheChunk, setBeginingOfTheChunk] = useState<number>(0);
  const [endOfTheChunk, setEndOfTheChunk] = useState<number>(chunkSize);
  const [fileToBeUpload, setFileToBeUpload] = useState<any>({});
  const [counter, setCounter] = useState<number>(1);
  const [fileExtension, setFileExtension] = useState<string>("");
  const [keys, setKeys] = useState<any[]>([]);
  const [state, setState] = useState<UploadObject>({
    selectedKey: "",
    fileName: ""
  })

  type UploadObject = {
    selectedKey: string,
    fileName: string
  }

  useEffect(() => {
    if (fileSize > 0) {
      fileUploadOnServer(counter);
    }
  }, [fileToBeUpload, progress]);
  
  useEffect(() => {
    const userId = localStorage.getItem("userId") || '{}';
    axios.get(
      `${domain}/Key/GetUserKeys/${userId}`, {
      headers: { "Content-Type": "application/json" },
    }
    ).then((res) => {
      setKeys((prevKeys) => [...prevKeys, res.data]);
    }).catch((exception) => {
      console.log(exception);
    })
  }, [])

  const resetChunkProperties = () => {
    setProgress(0);
    setCounter(1);
    setBeginingOfTheChunk(0);
    setEndOfTheChunk(chunkSize);
  };

  const handleFileChange = (event: any) => {
    const files = event.target.files;
    for(let i = 0; i < files.length; i++){
      resetChunkProperties();

      if(files.length > 1){
        setState({...state, fileName: state.fileName+i});
      }

    const _file = files[i]
    setFileSize(_file.size);

    const _totalCount =
      _file.size % chunkSize === 0
        ? _file.size / chunkSize
        : Math.floor(_file.size / chunkSize) + 1; // Total count of chunks will have been upload to finish the file
    setChunkCount(_totalCount);

    setFileToBeUpload(_file);
    const extension = "." + _file.name.split(".").pop();
    setFileExtension(extension);
    }
  };

  const fileUploadOnServer = (counter: number) => {
    setCounter(counter + 1);
    if (counter <= chunkCount) {
      var chunk = fileToBeUpload.slice(beginingOfTheChunk, endOfTheChunk);
      uploadChunk(chunk);
    }
  };

  const uploadChunk = async (chunk: any) => {
    try {
      const id = localStorage.getItem("userId") || '{}';
      const response = await axios.post(
        `${domain}/File/Upload/`,
        chunk,
        {
          params: {
            userId: id,
            keyId: state.selectedKey,
            fileName: state.fileName + fileExtension,
            currentChunkNo: counter,
            totalChunks: chunkCount,
          },
          headers: { "Content-Type": "application/json" },
        }
      );
      if (response.status === 200) {
        setBeginingOfTheChunk(endOfTheChunk);
        setEndOfTheChunk(endOfTheChunk + chunkSize);
        if (counter === chunkCount) {
          setProgress(100);
        } else {
          var percentage = (counter / chunkCount) * 100;
          setProgress(percentage);
        }
      } else {
        console.log("Error Occurred");
      }
    } catch (error) {
      console.log("error", error);
    }
  };

How do you declare and redefine variables in CSS for abstraction?

I have an animation for fading the header in on a page:

h1{
    animation: fadeIn linear 3s;
    -webkit-animation: fadeIn linear 3s;
    -moz-animation: fadeIn linear 3s;
    -o-animation: fadeIn linear 3s;
    -ms-animation: fadeIn linear 3s;
}
@keyframes fadeIn {
    0% {opacity:0;}
    33% {opacity:0;}
    100% {opacity:1;}
}

@-moz-keyframes fadeIn {
    0% {opacity:0;}
    33% {opacity:0;}
    100% {opacity:1;}
}

@-webkit-keyframes fadeIn {
    0% {opacity:0;}
    33% {opacity:0;}
    100% {opacity:1;}
}

@-o-keyframes fadeIn {
    0% {opacity:0;}
    33% {opacity:0;}
    100% {opacity:1;}
}

@-ms-keyframes fadeIn {
    0% {opacity:0;}
    33% {opacity:0;}
    100% {opacity:1;}
}

Now I want to use the exact same animation to fade in the text below the header. That means I have to copy-paste this entire code a second time, and the only thing I am changing is the percent opacity in which the fading starts, as well as the duration of the animation. Is there a way to just use the same fadeIn animation but declare a variable? Here is my pseudocode on what I want to do:

var startingPercentage; /*Somehow implementing a JS variable into CSS*/

h1{
    startingPercentage = 33; /*Define startingPercentage as equal to 33 for this first animation*/

    animation: fadeIn linear 3s;
    -webkit-animation: fadeIn linear 3s;
    -moz-animation: fadeIn linear 3s;
    -o-animation: fadeIn linear 3s;
    -ms-animation: fadeIn linear 3s;
}
h2{
    startingPercentage = 75; /*Redefine starting percentage as 75, so it starts fading in 3 seconds after the page loads*/

    animation: fadeIn linear 4s;
    -webkit-animation: fadeIn linear 4s;
    -moz-animation: fadeIn linear 4s;
    -o-animation: fadeIn linear 4s;
    -ms-animation: fadeIn linear 4s;
}
@keyframes fadeIn {
    0% {opacity:0;}
    startingPercentage% {opacity:0;} /*Use the abstracted variable instead of rewriting all this code repeatedly*/
    100% {opacity:1;}
}

@-moz-keyframes fadeIn {
    0% {opacity:0;}
    startingPercentage% {opacity:0;}
    100% {opacity:1;}
}

@-webkit-keyframes fadeIn {
    0% {opacity:0;}
    startingPercentage% {opacity:0;}
    100% {opacity:1;}
}

@-o-keyframes fadeIn {
    0% {opacity:0;}
    startingPercentage% {opacity:0;}
    100% {opacity:1;}
}

@-ms-keyframes fadeIn {
    0% {opacity:0;}
    startingPercentage% {opacity:0;}
    100% {opacity:1;}
}

How would I do this in CSS? Is there a way to use JavaScript variables within CSS?

how to merge and record multiple media stream into one and export it in mp4 format in react js #webrtc

how can I record multiple audio or video streams into one file and export them in mp4 format in react js?
I am using webrtc technology to create a video chat application
in this react app I have two streams one is a local one and another one is a remote stream coming from another user in the browser.
so how can I record that two-stream into one and export the recorded file in mp4 format?

Transfer data between server and client using XMLHttpRequest object, handle JSON – JavaScript

Transfer data between server and client using XMLHttpRequest object, handle JSON files and work with objects in JavaScript

question 1 :
Write a java-script program (in a file named Targil1Q1.html), which requests a GET request
Using the XMLHttpRequest object from the PHP program (Targil1Q1.php (, send to it) next to
The client (the data file attached to the job named mock_data.json whose top looks like this:

 [
 {
 "id":1,
 "first_name":"Florina",
 "last_name":"Head",
 "email":"[email protected]",
 "gender":"Female",
 "ip_address":"193.117.115.240"
 },
 {
 "id":2,
 "first_name":"Lusa",
 "last_name":"Ayling",
 "email":"[email protected]",
 "gender":"Female",
 "ip_address":"247.233.187.26"
 },
 …
 ]

The HTML program will ask the user using a simple person ID number form. also,
The JavaScript program will convert the JSON it received to a JS object and print it in the center
The document as a table containing headings and the details of the person the user entered the identification number
His. The table should show according to the following example that shows the column headings and the row
In which the details of the person with – 1
Image table

Question 2:

Write the HTML program in a file named Targil1Q2.html (which you will ask the user to use
A simple form for a person’s identification number. Write java-script code) inside Targil1Q2.html (which requests
Request a POST with parameters using the XMLHttpRequest object from the PHP program
(Targil1Q2.php (Read the data file mock_data.json. In the program request parameter
Send the person’s ID.
The PHP program will read the mock_data.json file and generate the HTML code of a table that contains it
Titles and the details of the person the user entered his ID number, and will send the table
Next to the client, where the table will be printed according to the following example that shows the column headings and
The line in which the person’s details with -1
Image table

Question 3:

Write a JavaScript program (in a file named Targil3Q1.html), which requests a POST request
Using the XMLHttpRequest object from the PHP program (Targil3Q1.php (, send to it) next to
The client (the data file attached to the job named quiz.json) image of him on the next page (.
The HTML program will calculate using the JavaScript program will convert the JSON it received
To the JS object.
The program through input that describes the topics of the question areas (sport, maths) will allow
The user has to choose the type of question the user will answer (math or sports).
Note that the question areas need to be taken from the object) in the present file these are the keys
“sport”, “maths” (- you need to take into account that the file can contain many more domains
From those in the current file, that is, you do not know in advance what the topics are and how many there are – you
This information is extracted from the object.
The HTML program will be calculated using the JavaScript program and will generate a random number by number
The questions in the selected field to be extracted from the object. For example in math there are 2 questions.
And the program knows this from the object using the array size of the options key. how
Random book computers read on the web (really not complicated – Google search)
The question selected for the user correctly when the options of the answers will be input of
Radio buttons that allow only one correct answer. Note the key language of the question is visible
Like for example q2, which means you will have to connect the number of the question drawn with the string “q”, in a jug
Obtain the appropriate key for the question in the object.
The user will select the correct answer and the program will tell him whether the answer is correct or not)
Know it from the object (answer key)

Bonus question:
Allow the user to answer another question after answering a question
) That will be displayed instead of the previous question (and answer it. The program will keep some successful questions)
The user answers and informs her at the end of the game (let’s say after 4 questions (about some of which she answered)
Right.
Code Image

Two code files needed

mock_data.json


[
   {
"id":1,
"first_name":"Florina",
"last_name":"Head",
"email":"[email protected]",
"gender":"Female",
"ip_address":"193.117.115.240"
   },
   {"id":2,"first_name":"Lusa","last_name":"Ayling","email":"[email protected]","gender":"Female","ip_address":"247.233.187.26"},
   {"id":3,"first_name":"Marguerite","last_name":"Peirson","email":"[email protected]","gender":"Female","ip_address":"241.171.45.22"},
   {"id":4,"first_name":"Rebeka","last_name":"Brabbs","email":"[email protected]","gender":"Female","ip_address":"44.228.21.181"},
   {"id":5,"first_name":"Ode","last_name":"Leeder","email":"[email protected]","gender":"Male","ip_address":"203.181.82.15"},
   {"id":6,"first_name":"Sly","last_name":"Breeder","email":"[email protected]","gender":"Male","ip_address":"26.91.12.31"},
   {"id":7,"first_name":"Thorvald","last_name":"Bridges","email":"[email protected]","gender":"Male","ip_address":"145.127.204.252"},
   {"id":8,"first_name":"Alonso","last_name":"Pitsall","email":"[email protected]","gender":"Male","ip_address":"41.27.229.172"},
   {"id":9,"first_name":"Thor","last_name":"Lynde","email":"[email protected]","gender":"Male","ip_address":"130.116.61.0"},
   {"id":10,"first_name":"Parrnell","last_name":"Haysman","email":"[email protected]","gender":"Male","ip_address":"214.121.248.210"},
   {"id":11,"first_name":"Rainer","last_name":"Walcot","email":"[email protected]","gender":"Male","ip_address":"40.153.144.192"},
   {"id":12,"first_name":"Nickola","last_name":"Staples","email":"[email protected]","gender":"Male","ip_address":"205.176.9.60"},
   {"id":13,"first_name":"Langston","last_name":"Penfold","email":"[email protected]","gender":"Male","ip_address":"171.115.137.183"},
   {"id":14,"first_name":"Mirella","last_name":"Bodill","email":"[email protected]","gender":"Bigender","ip_address":"79.48.191.67"},
   {"id":15,"first_name":"Dunstan","last_name":"Strapp","email":"[email protected]","gender":"Male","ip_address":"232.175.141.13"},
   {"id":16,"first_name":"Talbot","last_name":"Pactat","email":"[email protected]","gender":"Male","ip_address":"99.94.6.23"},
   {"id":17,"first_name":"Beverly","last_name":"Howick","email":"[email protected]","gender":"Female","ip_address":"144.79.46.36"},
   {"id":18,"first_name":"Aubrette","last_name":"Ansteys","email":"[email protected]","gender":"Female","ip_address":"132.195.181.226"},
   {"id":19,"first_name":"Chaddie","last_name":"Kunkler","email":"[email protected]","gender":"Genderqueer","ip_address":"238.32.127.190"},
   {"id":20,"first_name":"Rodrigo","last_name":"Lillie","email":"[email protected]","gender":"Male","ip_address":"21.73.42.39"}
]

Quiz.jon


{
"quiz": {
"sport": {
"q1": {
"question":"Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
               ],
"answer":"Huston Rocket"
           }
       },
"maths": {
"q1": {
"question":"5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
               ],
"answer":"12"
           },
"q2": {
"question":"12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
               ],
"answer":"4"
           }
       }
   }
}


Thank you very much for the help really thank you to whoever will help

How to get radio buttons to work within document.getElementById

The html code in the “document.getElementById” section will work when it is stand along, but although it produces the radio buttons when nested inside “document.getElementById” the buttons don’t work. I wonder if its to do with nesting the “document.getElementById”

     <span id="Item1"></span>

     <script>

     document.getElementById("Item1").innerHTML = '<center><table bgcolor="#ddceff" width="550" border="2"><TR><TD><center>TEST<BR><audio id="player" src="https://media.radiodgh.com:8443/stream"></audio><div><button onclick="document.getElementById("player").play()">Play</button><button onclick="document.getElementById("player").pause()">Pause</button><button onclick="document.getElementById("player").volume += 0.1">Vol +</button><button onclick="document.getElementById("player").volume -= 0.1">Vol -</button></div></center></font></center></TD></TR></TABLE>'

     </script>

Sort Arr Numbers MM/DD/YYYY When they’re strings?

How do I sort these descending correctly? I’ve tried arr.sort() arr.sort().reverse() , looked all over stack overflow … and I cannot find a way to do this. Everything tries to sort them but does it wrong.

[
  '1/19/2024',  '1/20/2023',
  '10/21/2022', '11/18/2022',
  '12/16/2022', '3/17/2023',
  '6/10/2022',  '6/16/2023',
  '6/17/2022',  '6/21/2024',
  '6/24/2022',  '6/3/2022',
  '6/31/2022',  '7/15/2022',
  '7/8/2022',   '8/19/2022',
  '9/15/2023',  '9/16/2022'
]

Then I need to take those and turn them into the actual month. Jan, Feb, etc. instead of the numerical value …

How to put javascript variables from a form into a config file

I have a form (in Caspio Bridge) that the user fills out to create an event in a calendar. I’m using an ‘Add to Calendar’ module from an outside source (https://github.com/jekuer/add-to-calendar-button) to create a file for downloading to various calendars (google, ical, etc.).

In the Caspio form <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/assets/css/atcb.min.css"> and <script src="https://cdn.jsdelivr.net/npm/[email protected]" defer></script> are referenced to pull in the various files needed.

In the Caspio form a button click creates a config file that is used to create the download file and open the download options buttons.

I need to pull variables (event title, description, start date/time, end date/time) from the form, after the user enters data, and use those variables in creating the config file when the user clicks the Submit button. How is this done? Also, I can only alter the code shown here, not the referenced files.

Here are the javascript variables that get the user’s input from the form:

var v_name = document.getElementById('InsertRecordTasksTimeline_Title').value;
var v_note = document.getElementById('InsertRecordTasksTimeline_Notes').value;
var v_location = document.getElementsByName('InsertRecordTasksTimeline_Location')[0].value;

 Stamp = new Date(document.getElementById('InsertRecordTasksTimeline_CalDate').value);
 Hours = Stamp.getHours()
 Mins = Stamp.getMinutes();
v_BeginDate=('' + Stamp.getFullYear() +"-"+ (Stamp.getMonth()+1) + "-" + Stamp.getDate() +"T"+  Hours + ":" + Mins);

Stamp2 = new Date(document.getElementById('InsertRecordTasksTimeline_CalEnd').value);
 Hours = Stamp2.getHours()
 Mins = Stamp2.getMinutes();
v_EndDate=('' + Stamp2.getFullYear() +"-"+ (Stamp2.getMonth()+1) + "-" + Stamp2.getDate() +"T"+  Hours + ":" + Mins);

And here is the basic button that creates the config file: <button id="default-button" name="submitevent3">Submit</button>

Below is the code I have in the Caspio form that creates the config file, opens the download button options, and downloads a calendar file (.ics, etc). Note, for the values in this example there are just placeholders.

I somehow need to get the variables v_name, v_note, v_BeginDate, v_EndDate into the Config file so that name:v_name, description:v_note, startDate:v_BeginDate, endDate:v_EndDate. How would that be done?

 const config = {

    "name": "event title vale",
    "description": "event note value",
    "startDate" : "2022-06-01T10:15",
    "endDate": "2022-06-01T12:30",
    "location":"event location",
    options: ["Google", "Apple","Microsoft365"],
    timeZone: "currentBrowser",
    trigger: "click",
    iCalFileName: "Reminder-Event",
  }
  const button = document.querySelector('#default-button')
  button.addEventListener('click', ()=> atcb_action(config, button)

)