React, React-three-fiber is bugging when being passed state as props

Basically I’m rendering a ThreeJS scene in react..
The component waits for a user to upload a file, to then parse the file and create a scene.

This is the render:

  return (
    <Container>
    Input NBT file <br/>
    <input type="file" onChange={handleChange}></input>
    {renderHandler()}
    </Container>
  )

Component declaration, state declaration, and a static array I have named blockState

const Upload = () => {
    const [scene , setScene] = React.useState([]);

    // handleUpload = (event) => {
    //     console.log('Success!');
    // }

    let blockState = [<TexturePlane x={0} y={6} z={0} rot={[-Math.PI / 2, 0, 0]}/>];

    function renderHandler(){
      console.log('[RENDER] calling...')


      if(scene.length == 0){
        console.log('[RENDER] Denied!')
        return(
          <div>
            Nothing is rendered..
          </div>
        )
      } else {
        return (

          <View top={[...blockState]}/> //This works

         // <View top={[...scene]} /> //This doesn't work 
        )
      }
    }

handleChange:

   function handleChange(event) {
        console.log(event.target.files);
        // console.log(event.target.files[0]); //file struc
        const file = event.target.files[0];
        var reader = new FileReader();
        reader.onload = (e) => {


            var x = nbt.parse(e.target.result, function(error, data) {
              if (error) { throw error; }
              parseNBT(data);
          });

        }
        reader.readAsArrayBuffer(file);
    }

Basically handleChange readers the file, decodes, and the parseNBT(data) callback is called.

    function parseNBT(input) {
      console.log('Parsing...');

      //Does stuff
      setScene(scene.push(<TexturePlane x={3} y={3} z={0} rot={[-Math.PI / 2, 0, 0]}/>));
    }

The issue i’m having here is that when I’m trying to render the View Component (in renderHandler) passing in the scene state, it throws this error:
error 1
error 2

Whereas, when I use blockState, it renders just fine: (Works with & without spread syntax)
using blockState, works with and without spread syntax

I’ve console.log’d blockState & scene, they are indentical objects, it’s weird how when I’m passing in scene it isn’t working;
enter image description here

Source of the problem: (the renderHandler calling View component)

    function renderHandler(){
      console.log('[RENDER] calling...')


      if(scene.length == 0){
        console.log('[RENDER] Denied!')
        return(
          <div>
            Nothing is rendered..
          </div>
        )
      } else {
        return (
          <View top={scene}/>
        )
      }
    }

View Component:

import React, { Suspense } from 'react'
import Input from 'react-bootstrap/InputGroup'

import { Canvas } from "@react-three/fiber";
import { OrbitControls, softShadows } from "@react-three/drei";

import {Container} from "react-bootstrap";
import Box from './Box';
import TexturePlane from './TexturePlane';
import DisplayPlane from './DisplayPlane';

softShadows()

const View = (props) => {

  let top = props.top;

  return (

<Container>
  <Canvas shadows style={{ position: "relative", width: 750, height: 750 }}  gl={{ antialias: false }}>
  <ambientLight intensity={0.9} />

  <directionalLight 
  castShadow
  position={[9, 9, 9]} 
  intensity={1.9}  
  shadow-mapSize-width={1024}
  shadow-mapSize-height={1024}
  shadow-camera-far={100}
  shadow-camera-left={-10}
  shadow-camera-right={10}
  shadow-camera-top={10}
  shadow-camera-bottom={-10}

  />

  <OrbitControls enableZoom = {true} />
  <Suspense fallback={null}>

    {/*Generate scene here: */}
    {/*bottom: */}

    {top}

    {/* top */}


    <DisplayPlane/>

    </Suspense>
  </Canvas>
</Container>
);}

export default View

And TexturePlane is just a plane render component

control pixel to contant if check

i have a problem. i’m using javascript and i’m always trying to make a faster code.

so i create an app that check the pixel position.

if your pixel pointer is in the target position, the target make an action..
so if your mouse pass on pixel and the software must understand the pointer pixel is there.

thats the problem…
i dont know any pixel check on system so i did this code

    <script>
var pixelred    = 200 + "px"
var targetpoint = 0 + "px"

if(targetpoint.style.top === pixelred.style.top){
alert I'm here
}
   </script>

But when i set this to a function for loop to create a lot of places if dont work when the point cross the targetpixel

    <script>
var targetpoint = 0 + "px"

for (let index = 0; index < 10; index++) {
var randomplaces =  Math.floor(Math.random(200 - 0) * 200)
let pixelred    = randomplaces + "px"

    if(targetpoint.style.top === pixelred.style.top){
alert(I'm here)

document.body.innerHTML += pixelred
}
}
   </script>

i guess if i set the target position to array its going to work, but, if i do it i will not have the fast performance, because all the time they must find in 1000 diferent numbers if they are or not equal my ask.

do you have any idea?

Apps Script – Searching an array for a string and return true or false if that string is present

I am using Apps Script with Google Sheets. I have written some code to get the value in a cell and save it to a variable. I then created an array with all those variables. I want to be able to look through the array and look for the word “fail” and return true if it is present or false if it is not present. It only has to match once in the array for it to be true.

This is what I have so far:

function myFunction() {

 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var activeSheet = ss.getActiveSheet();

  for(var i = 20;i<=120,i++){

      var main = activeSheet.getRange(i, 8).getValue();
      var state = activeSheet.getRange(i, 9).getValue();
      var scroll = activeSheet.getRange(i, 10).getValue();;
      var log = activeSheet.getRange(i, 11).getValue();

      const testArray = [main, state, scroll, log];
//need some code here to look for the string "fail" in the array and if it is there, return true, otherwise return false.
   
  }
}

Calling API with Javascript html

What is the correct way to call this API? The api url is: https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd

I tried with this code

<p id="demo">
 </p>
 <script>
  var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.bitcoin;
        }
    };
    xmlhttp.open("GET", "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" + new Date().getTime(), true);
    xmlhttp.send();
 </script>

however the value I get is [object Object]. I want to get the value in “usd”.

Where am I wrong? Thx

Replaces myObj with myObj.usd but returns null value

Accessing URL Parameters react doesn’t work

I am trying to display h2 events on my page and when I click on URL category_events and notations too.

`App.js:

import './App.css';
import React, { Component } from 'react'
// import Header from './components/Header';
import Events from './components/Events/Events';
import Date from './components/Date/Date';
import Accueil from './components/Accueil/Accueil';
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';




function App() {
  return (
    <div className="wrapper">
      <h1>Marine Mammals</h1>
    <BrowserRouter>
    <nav>
      <ul>
        <li><Link to="/events">Events</Link></li>
        <li><Link to="/date">Date</Link></li>
        <li><Link to="/accueil">Accueil</Link></li>
        <li><Link to="/events/Category_events">Category Events</Link></li>
        <li><Link to="/events/Notations">Notations</Link></li>

      </ul>
    </nav>
    
      <Routes>
         
        
      
        <Route path="/Date"/>   
        <Date/>
        </Route>
        
        <Route exact path="/events"/>  
          <Events/>
          </Route> 

        <Route path="/events/;type"/>  
           <Events/>
          </Route>
          



      </Routes>
    </BrowserRouter>

    </div>
  );
}



export default App;

Events.js:

import React from 'react';
import { useParams } from 'react-router-dom';
import Category_events from './Category_events';
import Notations from './Notations';


export default function Events(){
  const { type } = useParams();

  


  return (
    <>
      <h2>Events</h2>
      {type === 'Category_events' && <Category_events />}
      {type === 'Notations' && <Notations/>}

      
    </>
  );
}

I got this error:
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /home/thibaut/fastmeet/src/App.js: Expected corresponding JSX closing tag for <Routes>. (35:8)

33 | <Route path=”/Date”/>
34 | <Date/>

35 | </Route>
| ^
36 |
37 | <Route exact path=”/events”/>
38 | <Events/>

Trying to do multiple checks on values from API and separating them into different functions

I’m trying to learn how to use APIs and filter the information based on the values in the API.

I’ve figured out how to use if/else if/else statements to filter if a character is dead or alive etc. but when there are multiple checks I need to do I run into issues of functions being hundreds of lines long and them becoming a mess.

I’ve tried writing functions for each check I need to do, and I’m curious if there is an easier way to do this.

This is how I tried doing it, by using if/else if/else statements.

My problem comes up when I need to for example check if a character is dead, if they have a profile picture and what house they belong to. So that I can push their profile picture to the site if they have one and push a default picture if they don’t, still checking and showing if they are dead/alive and what house they belong to

{
name: "Harry Potter",
alternate_names: [ ],
species: "human",
gender: "male",
house: "Gryffindor",
dateOfBirth: "31-07-1980",
yearOfBirth: 1980,
wizard: true,
ancestry: "half-blood",
eyeColour: "green",
hairColour: "black",
wand: {
wood: "holly",
core: "phoenix feather",
length: 11
},
patronus: "stag",
hogwartsStudent: true,
hogwartsStaff: false,
actor: "Daniel Radcliffe",
alternate_actors: [ ],
alive: true,
image: "http://hp-api.herokuapp.com/images/harry.jpg"
}
let studentArray = [];

async function getStudents(url) {
  const student = await fetch(url);
  const jsondata = await student.json();
  jsondata.forEach((student) => {
    studentArray.push(student);
  });
}

function listStudents() {
  const student = document.getElementById("name");
  for (let i = 0; i < studentArray.length; i++) {
    if (studentArray[i].alive == false) {
      student.innerHTML += `<div class="card">
    <img class="pfp" src="${studentArray[i].image}"</img>
      <div class="container">
      <ul>
      <li><h2>Name:${studentArray[i].name}</h2></li>
      <li><h2>House:${studentArray[i].house}</h2></li>
      <li><h2>Age:${studentArray[i].yearOfBirth}</h2></li>
      <li><h3>Dead</h3></li>
        </ul>
      </div>
    </div>`;
    } else if (studentArray[i].yearOfBirth == "") {
      student.innerHTML += `<div class="card">
    <img class="pfp" src="${studentArray[i].image}"</img>
      <div class="container">
        <ul>
        <li><h2>Name:${studentArray[i].name}</h2></li>
        <li><h2>House:${studentArray[i].house}</h2></li>
        <li><h2>Age:Unknown</h2></li>
        <li><h4>Alive</h4></li>
        </ul>
      </div>
    </div>`;
    } else {
      student.innerHTML += `<div class="card">
    <img class="pfp" src="${studentArray[i].image}"</img>
      <div class="container">
        <ul>
        <li><h2>Name:${studentArray[i].name}</h2></li>
        <li><h2>House:${studentArray[i].house}</h2></li>
        <li><h2>Age:${studentArray[i].yearOfBirth}</h2></li>
        <li><h4>Alive</h4></li>
        </ul>
      </div>
    </div>`;
    }
  }
}

getStudents("http://hp-api.herokuapp.com/api/characters/students").then(() => {
  listStudents();
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="/testing/script.js"></script>
    <link rel="stylesheet" href="/testing/styles.css" />
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <main>
      <div id="name" class="container"></div>
    </main>
  </body>
</html>

How to unload dynamic imports in javascript?

So basically, I have a json file that defines what to load when a user logs in. This includes javascript files. When a different user logs in, the previous stuff needs to be unloaded without a page refresh.

I’m making use of the javascript dynamic import

 modules[moduleId] = await import(url);

I’m finding, that even after I clear the “modules”-variable in to an empty object, the event listeners defined within the dynamically imported module are still firing. I’m assuming most everything else defined within that closure is still taking up memory also.

Now if I were to abuse the login/logout like this, I’m assuming I would end up with memory leak issues. How do I make sure the modules loaded in to an object reference are properly unloaded when they are no longer needed?

I’m working with pure js here with no access to outside libraries or tools.

Problem to connect angular app and react?

i want to connect two app ,one created in react an the second in angular.Angular app is a login component and the react is a list of products.I imported a script tag in html document in angular app but I dont render a component in a dom.Product List is empty(not rendered)I have some error in console

Uncaught Error: Minified React error #200; visit https://reactjs.org/docs/error-decoder.html?invariant=200 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at Object.t.render (react-dom.production.min.js:296:48)
    at index.js:7:1
    at index.js:17:1
<app-header></app-header>

<mat-sidenav-container class="full-height-container">
    <mat-sidenav #sidenav mode="over" class="content-padding" [fixedInViewport]="true" [fixedTopGap]="60" [fixedBottomGap]="0" [opened]="false">
        <app-login></app-login>
    </mat-sidenav>
    <mat-sidenav-content>
        <div class="content-padding">
            <div [hidden]="hideProducts" class="split left">
                <h2>Product List</h2>
                <div id="root"></div>
            </div>

            <div [hidden]="hideShoppingCartRegion" class="{{ shoppingCartStyles }}">
                <h2>Shopping Cart</h2>
                <p *ngIf="hideShoppingCart">Please login to view your shopping cart</p>
                <div [hidden]="hideShoppingCart" id="vue-application"></div>
            </div>
            <div [hidden]="hideOrderPlaced" class="split left">
                <h2>Order Placed</h2>
                <p>&nbsp;</p>
                <p>Thank you, {{ username }}.</p>
                <p>Your order has been placed.</p>
                <p>- The Switch Sales team.</p>
            </div>
        </div>
    </mat-sidenav-content>
</mat-sidenav-container>

<router-outlet></router-outlet>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>MyApp</title>
    <base href="/" />
    <script src="/assets/MicroEventBus.js"></script>
    <script src="/assets/main.613915a5.js"></script>
    <link href="/assets/main.ca0fa319.css" rel="stylesheet" />
    <meta name=" viewport " content="width=device-width, initial-scale=1 " />
    <link rel="icon " type="image/x-icon " href="favicon.ico " />
    <link rel="preconnect " href="https://fonts.gstatic.com " />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap " rel="stylesheet " />
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons " rel="stylesheet " />
</head>

<body class="mat-typography">
    <app-root></app-root>
</body>

</html>

enter image description here

This is how I expected to see:

enter image description here

Firefox and Safari setting incorrect header for ContentType when using FormData

We have a file upload code section where we use Form data to send to the file to the backend service.

let formData = new FormData();
formData.append('classFile', values.file || new Blob(), values.file ? values.file.name : '');

We make a http post request to the backend to send this data. We are noticing that the Content Type is set correctly to multipart/formdata on chrome
Chrome request header
whereas Firefox/Safari sets them to application/json.
Firefox request header

Why am i getting Cannot read properties of null (reading ‘addEventListener’) error? [duplicate]

I am getting a cannt read properties of null(add event listener) error.

html code

<!DOCTYPE html>
<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" />
    <title>Landing</title>
    <script src="script.js"></script>
  </head>
  <body>
    result:
    <div id="optionOne" class="option1">hello</div>
    <div id="optionTwo" class="option2">friend</div>
    <button id="btn">click here</button>
  </body>
</html>

js code

const element = document.getElementById("btn");
element.addEventListener("click", myFunction);

function myFunction() {
  console.log("hello world")
}

please help .

Download document using react(via API call) and show browser spinner instead of custom application spinner

I am trying to download documents uploaded in the application via fetchHandlers. While doing so I am making an API call and once API response(BLOB data) is available creating a object URL to download the document. Below is the code:

  downloadDocument(file.id, clientId)
    .then((res) => {
      const urlToDownload = URL.createObjectURL(res);
      const link = document.createElement("a");
      link.href = urlToDownload;
      link.setAttribute("download", `${file.name}`);

      // Append to html link element page
      document.body.appendChild(link);

      // Start download
      link.click();

      // Clean up and remove the link
      link.parentNode.removeChild(link);
    })
    .catch((err) => {
      console.log(err);
    });
};

However, if the document size is big it takes a lot of time there is a need to show that the download is in progress. Google and Gmail handles this use case(download attachments) by showing the download in the bottom download bar and the spinner comes as part of the document icon. However using the above the download happens independently and the spinner in the taskbar appears only for a brief moment while the object url is clicked.

How can we use the inbuilt browser experience to show the spinner. This experience is visible in Google Chrome.

Migrating Chrome Extension (Twitch AdBlocker) from Manifest v2 to v3

Today an author of a beloved Chrome extension decided to add his amazon reflink secretly and also deleted the GitHub repository. I didn’t really like that move, and unfortunately that extension is still running with Manifest v2, but Manifest v3 is required in order to publish it to the Chrome Webstore.

The extension does some inline-scripting which is not supported in v3 anymore. I’ve tried to load a .js-file with the inline-scripting content besides the content.js which is the main javascript file. Unfortunately, that solution did not work. The extension is supposed to block ads on Twitch.tv.

I’ve created a GitHub repository with the source code. It would be amazing if someone could help out.

In the dev-branch you can see the “Manifest v3” code. master is sill v2.

https://github.com/cleanlock/VideoAdBlockForTwitch

How to pass as a props an array of String and JSX with NextJs?

i passed as a props an array of strings an JSX but there is an error message “Missing “key” prop for element in arrayeslintreact/jsx-key “

<Sec1Header
    
      MainText={[
        "Your ",
        <span className='text-red-400'>
          Trusted
        </span>,
        " Development Partner",
      ]}
  
    />

I’m doing all of that to just try to color the text “Trusted” with different colors and not change the div dynamic