React route how to get to the page i want

So, i have a code that is using react-route, and i have a few pages, but when i get to one of them, i can’t enter the others, since the URL gets stuck in the actual page, is there any way to solve this? When i go from the app page, to the CheckOut page, my url gets like this: localhost:3000/CheckOut, and when i try to move to the Comprar page, its gets like this: localhost:3000/CheckOut/Comprar, which is not working, and when i manually write the url like this: localhost:3000/Comprar, it do work, i want to know how can i get to the Checkout page, and then go to the Comprar page, and the URL should look like this: localhost:3000/Comprar.

App.js:

import './styles/App.css';
import React, {useState} from "react"
import DefineDestino from './components/DefineDestino';
import {BrowserRouter as Router, Routes, Route} from "react-router-dom";
import CheckOut from './pages/CheckOut';
import Comprar from './pages/Comprar';

function App() {
  const [estadoOrigem, setEstadoOrigem] = useState()
  const [estadoDestino, setEstadoDestino] = useState()
  return (
      <Router>
        <div className="App">
          <div className="mainContent">
            <h1>Escolha um destino.</h1>
              <div className="estados">
                <h1>Local de Origem</h1>
                <select value={estadoOrigem} onChange={e => setEstadoOrigem(e.target.value)}>
                    <option>Rio de Janeiro</option>
                    <option>São Paulo</option>
                    <option>Minas Gerais</option>
                    <option>Brasília</option>
                    <option>Pará</option>
                    <option>Ceará</option>
                    <option>Paraná</option>
                    <option>Mato Grosso</option>
                </select>
            </div>
            <div className="estados">
              <h1>Destino Final</h1>
              <select className="select" value={estadoDestino} onChange={e => setEstadoDestino(e.target.value)}>
                  <option>Rio de Janeiro</option>
                  <option>São Paulo</option>
                  <option>Minas Gerais</option>
                  <option>Brasília</option>
                  <option>Pará</option>
                  <option>Ceará</option>
                  <option>Paraná</option>
                  <option>Mato Grosso</option>
              </select>
          </div>
              < DefineDestino origem={estadoOrigem} destino={estadoDestino}></DefineDestino>
              <Routes>
                <Route path="/CheckOut" element={<CheckOut />}></Route>
                <Route path="/Comprar" element={<Comprar />}></Route>
              </Routes>
          </div>
        </div>
      </Router>
    );
}

DefineDestino.js:

import React, {useState} from "react"
import { Link } from "react-router-dom";
import '../styles/DefineDestino.css'

export default function DefineDestino(props) {
    const [initialValue, setValue] = useState(0)
    const dados = {
        locais: [
            {
                estado: 'Rio de Janeiro', 
                aeroportos: 'Santos Dumont', 
                valor: 3000
            },
            {
                estado: 'São Paulo',
                aeroportos: 'Aeroporto Internacional de São Paulo-Guarulhos', 
                valor: 2500
            },
            {
                estado: 'Pará',
                aeroportos: 'Aeroporto Internacional de Belém', 
                valor: 1500
            },
            {
                estado: 'Minas Gerais',
                aeroportos: 'Aeroporto Internacional de Belo Horizonte-Confins', 
                valor: 1750
            },
            {
                estado: 'Brasília',
                aeroportos: 'Aeroporto Internacional de Brasília', 
                valor: 1600
            },
            {
                estado: 'Mato Grosso',
                aeroportos: 'Aeroporto Internacional de Cuiabá', 
                valor: 1350
            },
            {
                estado: 'Paraná',
                aeroportos: 'Aeroporto Internacional de Curitiba', 
                valor: 1200
            },
            {
                estado: 'Ceará',
                aeroportos: 'Aeroporto Internacional de Fortaleza', 
                valor: 1200
            }
        ]
    }
    
    var local = props.destino

    const increment = () => {
        return {
            type:'increment'
        }
    }

    function estadosReducer(state, action) {
        if (action.type === 'increment') {
            var item
            for (item of dados.locais) {
                if (item.estado === local) {
                    switch(local) {
                        case 'Rio de Janeiro':
                            setValue(initialValue + item.valor)
                            break
                        case 'São Paulo':
                            setValue(initialValue + item.valor)
                            break
                        case 'Pará':
                            setValue(initialValue + item.valor)
                            break
                        case 'Minas Gerais':
                            setValue(initialValue + item.valor)
                            break
                        case 'Brasília':
                            setValue(initialValue + item.valor)
                            break
                        case 'Mato Grosso':
                            setValue(initialValue + item.valor)
                            break
                        case 'Paraná':
                            setValue(initialValue + item.valor)
                            break
                        case 'Ceará':
                            setValue(initialValue + item.valor)
                            break
                    }
                }
            }
        }
    }

    return(
        <div>
            <h1>De: {props.origem}</h1>
            <h1>Para: {props.destino}</h1>
            <h1>Valor: {initialValue}</h1>
            <button onClick={() => estadosReducer(initialValue, increment())}><Link to={"CheckOut"}>Realizar Checkout</Link></button>
        </div>
    )
}

CheckOut.js:

import '../styles/App.css';
import { Link, BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Comprar from './Comprar';

function CheckOut(props) {
  return (
      <div className="CheckOut">
          <h1>Efetuar compra?</h1>
          <button><Link to={"Comprar"}>Comprar passagem</Link></button>
      </div>
  );
}

export default CheckOut;

CheckOut.js:

import '../styles/App.css';
import { Link, BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Comprar from './Comprar';

function CheckOut(props) {
  return (
      <div className="CheckOut">
          <h1>Efetuar compra?</h1>
          <button><Link to={"Comprar"}>Comprar passagem</Link></button>
      </div>
  );
}

export default CheckOut;

Comprar.js:

import '../styles/App.css';

function Comprar(props) {
  return (
    <div className="Compra">
        <h1>Compra efetuada! Boa viagem :)</h1>
    </div>
  );
}

export default Comprar;

TypeError: Cannot destructure property ‘setUser’ of ‘Object(…)(…)’ as it is undefined

I have a problem to set the user in my web page. I used AppContext where all the components to update the states are.When I run my code, it says that setUser is undefine, but I defined in AppContext and imported in App.jsx. Anyone can help? I saw others solution and it seems that const { setUser } = useContext(AppContext);have to be out of the component ,but shows an error.
This is App.jsx

import "./App.css";
import { Header } from "./components/header/Header";
import { Nav } from "./components/nav/Nav.jsx";
import { getUser } from "./services/users";
import { AppContext } from "./context/AppContext";
import { Notification } from "./components/notification/Notification";
import { Router } from "./routers/Router";

function App() {
  const { setUser } = useContext(AppContext);
  useEffect(() => {
    getUser().then((user) => {
      setUser(user);
    });
  }, [setUser]);
  return (
    <div>
      <Notification />
      <Nav />
      <Header />
      <Router />
      <AppContext />
    </div>
  );
}

export default App;

This is AppContext.jsx

import React,{ useState } from "react";
 import { usePagination } from "../components/utils/pagination.jsx";


export const AppContext = React.createContext();


export default function AppProvider({ children }) {
    const [user,setUser] = useState({})
    const [points, setPoints] = useState(0)
    const [products, setProducts] = useState([])
    const [reedemStatus, setReedemStatus] = useState({})
    const [history, setHistory] = useState([])


    const paginationList = usePagination(products, 16)
    const paginationHistoryList = usePagination(history, 16)

    const totalProducts = products.length
    const totalHistory = history.length

    const handlerAddPoint =(value)=>{
        const newUser = {...user}
        newUser.points = user.points + value
        setUser(newUser)
      }
    
      const handlerSubtractPoint =(points)=>{
        const newUser = {...user}
        newUser.points = user.points - points
        setUser(newUser)
      }
    return(
        <AppContext.Provider value={{user,
            setUser,  
            handlerAddPoint, 
            handlerSubtractPoint, 
            points,
            setPoints,  
            products, 
            setProducts, 
            totalProducts,
            paginationList,
            reedemStatus, 
            setReedemStatus,
            history,
             setHistory, 
             paginationHistoryList,
             totalHistory}}>
             {children}
        </AppContext.Provider>
    );
}

Accordion in a chrome ext using vanilla JS

I am looking to create a simple accordion within my chrome ext to display data. I am using the following JS tutorial but I seem to be struggling to register a click.

I have returned some data using the following:

//background.js

...

 // Looping through object's key value pair to place into divs
  for (const [key, value] of Object.entries(params)) {
    queryParams += `
      <div class="text-sm my-1">
        <span class="font-bold uppercase mr-1">${key}: </span><span class="font-normal font-mono capitalizev c-word-wrap">${value}</span>
      </div>
    `;
  }

  return (completeData += `
    <div class="element my-3">

      <div class="question flex justify-between pl-6 pr-12 py-4 bg-purple-500">
        <span class="text-base text-white font-bold">${pixelType}</span>
        <button id="btn">
          <i class="fas fa-plus-circle"></i>
        </button>
      </div>

      <div class="answer hideText">
        <span id="pixel-url" class="c-word-wrap text-sm font-mono">${pixelUrl}</span>
          <span id="query-params">${queryParams}</span>
      </div>

    </div>
 
  `);
};
...

I then have my logic in a separate file

//accordion.js

const elements = document.querySelectorAll('.element');

elements.forEach((element) => {
  let btn = element.querySelector('.question button');
  let icon = element.querySelector('.question button i');
  var answer = element.lastElementChild;
  var answers = document.querySelectorAll('.element .answer');

  btn.addEventListener('click', () => {
    console.log('btn clicked');
    answers.forEach((ans) => {
      let ansIcon = ans.parentElement.querySelector('button i');
      if (answer !== ans) {
        ans.classList.add('hideText');
        ansIcon.className = 'fas fa-plus-circle';
      }
    });

    answer.classList.toggle('hideText');
    icon.className === 'fas fa-plus-circle'
      ? (icon.className = 'fas fa-minus-circle')
      : (icon.className = 'fas fa-plus-circle');
  });
});

I have also tried to place the same logic in popup.js which didn’t work either. I am loading my scrips in like so…

popup.html

<!-- Scripts -->
    <script src="popup.js"></script>
    <script src="../background.js"></script>
    <!-- Accordion -->
    <script src="../fa.js"></script>
    <script src="../accordion.js"></script> 

If anyone can guide me in where I am going wrong here that would be great. I have also tried replicating the tutorial outside of a chrome ext and it works perfectly

Threejs Reactjs : TypeError: Cannot read properties of null (reading ‘addEventListener’)

I follow this tutorial : https://youtu.be/V8GnInBUMLo but… when I finish I got this error

TypeError: Cannot read properties of null (reading ‘addEventListener’)

I try to had if(element) inside my addeventlisters function but I got a new error:

TypeError: Cannot read properties of null (reading ‘appendChild’)

I think this error comes from my importation of ImageDistortion.js in Hero.js

ImageDistortion.js

import * as THREE from 'three';
import imageOne from '../img/1.jpg';
import imageTwo from '../img/3.jpg';
import vertex from './shaders/vertex.glsl';
import fragment from './shaders/fragment.glsl';


function lerp(start, end, t){
    return start * ( 1 - t ) + end * t;
}


let targetX = 0;
let targetY = 0;

const textureOne = new THREE.TextureLoader().load(imageOne);
const textureTwo = new THREE.TextureLoader().load(imageTwo);


class WebGL{
    constructor(){
        this.container = document.querySelector('.hero');
        this.links = [...document.querySelectorAll('.three--anim')];
        this.scene = new THREE.Scene();
        this.perspective = 1000;
        this.sizes = new THREE.Vector2(0,0);
        this.offset = new THREE.Vector2(0,0); // Positions of mesh on screen. Will be updated below.
        this.uniforms = {
            uTexture: {value: new THREE.TextureLoader().load(imageTwo)},
            uAlpha: {value: 0.0},
            uOffset: {value: new THREE.Vector2(0.0, 0.0)}
        }
        this.links.forEach((link, idx) => {
            link.addEventListener('mouseenter', () => {
                
                switch(idx){
                    case 0:
                        
                        this.uniforms.uTexture.value = textureOne;
                        break;
                    case 1:
                        this.uniforms.uTexture.value = textureTwo;
                        break;
                }
            })

            link.addEventListener('mouseleave', () => {
                this.uniforms.uAlpha.value = lerp(this.uniforms.uAlpha.value, 0.0, 0.1);
            });
        })
        this.addEventListeners(document.querySelector('h1'));
        this.setUpCamera();
        this.onMouseMove();
        this.createMesh();
        this.render()
        
    }

    get viewport(){
        let width = window.innerWidth;
        let height = window.innerHeight;
        let aspectRatio = width / height;

        return{
            width, 
            height, 
            aspectRatio
        }
    }

    addEventListeners(element){
        element.addEventListener('mouseenter', () => {
            this.linkHovered = true;
        })
        element.addEventListener('mouseleave', () => {
            this.linkHovered = false;
        })
    }

    setUpCamera(){
        window.addEventListener('resize', this.onWindowResize.bind(this))
        
        let fov = (180 * (2 * Math.atan(this.viewport.height / 2 / this.perspective))) / Math.PI;
        this.camera = new THREE.PerspectiveCamera(fov, this.viewport.aspectRatio, 0.1, 1000);
        this.camera.position.set(0, 0 , this.perspective);

        this.renderer = new THREE.WebGL1Renderer({antialias: true,alpha: true });
        this.renderer.setSize(this.viewport.width, this.viewport.height);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.container.appendChild(this.renderer.domElement)
    }

    createMesh(){
        this.geometry = new THREE.PlaneGeometry(1,1,20,20);
        this.material = new THREE.ShaderMaterial({
            uniforms: this.uniforms,
            vertexShader: vertex,
            fragmentShader: fragment,
            transparent: true,
            // wireframe: true,
            // side: THREE.DoubleSide
        })
        this.mesh = new THREE.Mesh(this.geometry, this.material);
        this.sizes.set(250, 350, 1);
        this.mesh.scale.set(this.sizes.x, this.sizes.y, 1);

        this.mesh.position.set(this.offset.x, this.offset.y, 0);
        
        this.scene.add(this.mesh);
    }
    onWindowResize(){
       
        this.camera.aspect = this.viewport.aspectRatio;
        this.camera.fov = (180 * (2 * Math.atan(this.viewport.height / 2 / this.perspective))) / Math.PI;
        this.renderer.setSize(this.viewport.width, this.viewport.height);   
        this.camera.updateProjectionMatrix();
    }

    onMouseMove(){
        window.addEventListener('mousemove', (e) => {
            targetX = e.clientX;
            targetY = e.clientY;
        })
    }

    render(){
        this.offset.x = lerp(this.offset.x, targetX, 0.1);
        this.offset.y = lerp(this.offset.y, targetY, 0.1);
        this.uniforms.uOffset.value.set((targetX- this.offset.x) * 0.0005 , -(targetY- this.offset.y) * 0.0005 )
        // this.mesh.scale.set(this.sizes.x, this.sizes.y)
        this.mesh.position.set(this.offset.x - (window.innerWidth / 2)  , -this.offset.y + (window.innerHeight / 2), 0);

        // set uAlpha when list is hovered / unhovered
        this.linkHovered 
        ? this.uniforms.uAlpha.value = lerp(this.uniforms.uAlpha.value, 1.0, 0.1) 
        : this.uniforms.uAlpha.value = lerp(this.uniforms.uAlpha.value, 0.0, 0.1);
       
        
            for(let i = 0; i < this.links.length; i++){
                if(this.linkHovered){
                    this.links[i].style.opacity = 0.2
                }else{
                    this.links[i].style.opacity = 1
                }
                
            
        }

        this.renderer.render(this.scene, this.camera);
        window.requestAnimationFrame(this.render.bind(this));
        
    }
    
}

new WebGL()

Hero.js

import React from 'react'
import ImageDistortion from './utils/ImageDistortion'


const Hero = () => {
    return (
        <div className="hero">
            <p>Hello.</p>
            <h1 id="three--anim--container">
                I'm <span className="name three--anim">Joris Delorme</span>, based in <span className="location three--anim">Lyon,France</span>.<br />
                I'm minimalist designer, developer and photographer.
            </h1>
        </div>
    )
}

export default Hero

addEventListener in a loop

I’m new in this nice community. I am a young student in computer science and I’m trying to develope a web based app to help both sighted people and people with visual empairment to learn typing. My project was blocked by the following problem:
Given a string, I need to verify that the user has pressed the key that corresponds to the first character. If it is correct, the program should test the next character, until the end of the string.
The most natural solutions seems to be a loop, like that:

        do {
        var checkCharacter=lessons[exerciceNumber][2].substr(charNumber, 1);
        document.addEventListener('keydown', testKey);
    }
    while (charNumber<=lessons[exerciceNumber][2].length-1);

When I run the script, nothing appears and it seems it doesn’t detect the pressed keys. Can you help me please?
Inorder to understand the context, I’ll attach the entire file.

<?php
include "config.php";
//Select fields from database
$sql="SELECT lesson_number, exercice_number, text FROM lessons";
$result=$conn->query($sql);
//Pass variables to javascript
$output="<script> var lessons=new Array(); ";
while ($row=$result->fetch_assoc()) {
    $output.="lessons.push([
        ".$row["lesson_number"].",
        ".$row["exercice_number"].",
        '".$row["text"]."']);";
}
$output.="</script>";
echo $output;
?>
<html>
<head>
    <title>Impara a scrivere</title>
</head>
<body>
    <h2 id="lesson"></h2>
    <p id="instructions"></p>
    <p id="check"></p>
    <p id="keyList"></p>
</body>
<script>
    //define variables
    var keys="";
    var exerciceNumber=0;
    var charNumber=0;
    //Function to play the sounds
    function sound(name) {
        var audio=new Audio(name+'.mp3');
        audio.play();}
    document.getElementById("lesson").innerHTML="Lezione "+lessons[exerciceNumber][0];
    document.getElementById("instructions").innerHTML="Esercizio "+lezioni[exerciceNumber][1]+": scrivi <b>"+lessons[exrciceNumber][2]+"</b>.";
    //function to check pressed keys
    funtion testKey(event) {
        if (event.key==checkCharacter) {
            sound ("right");
            keys+=event.key;
            document.getElementById("keyList").innerHTML=keys;
        } else {
            sound("wrong");
        }
    }
    //loop for the exercices
    do {
        var checkCharacter=lessons[exerciceNumber][2].substr(charNumber, 1);
        document.addEventListener('keydown', testKey);
    }
    while (charNumber<=lessons[exerciceNumber][2].length-1);
</script>
</html>

Chrome Extension that captures microphone audio AND cancels out system audio

I’m looking to write a Chrome Extension which records what the user speaks into their microphone on a Zoom. However, it needs to cancel out what other participants are saying (which the microphone picks up on, assuming no headphones). I know I can do this via a desktop application which separates the microphone and system audio and cancels out the system audio. But I am hitting a roadblock coming up w/ an alternative that would work via a Chrome extension. A workaround is to have the user install Krisp and select that as their microphone source (since Krisp separates system audio) but I’m looking for something not dependent on a desktop install. Am I missing anything obvious here? Thanks!

Issue with quick.db subtract

I have been trying to make a invite manager but when a user leaves it doesn’t remove a invite and add a leave, i am not sure whats the issue

  let user = db.get(`author_${member.guild.id}_${member.id}`)
  if (!user) {
    let channel = db.get(`leave_channel_${member.guild.id}`)
    if (!channel) return;
    member.guild.channels.cache.get(channel).send(`${member.username} has left, but i can't figure out who invited him.`)
    return
  }


  console.log(`user left`)
  db.add(`invites_${member.guild.id}_${user}.leaves`, 1)
  db.subtract(`invites_${member.guild.id}_${user}.invites`, 1)
  let channel = db.get(`leave_channel_${member.guild.id}`)
  if (!channel) return;
  let leave = db.get(`leave_message_${member.guild.id}`)
  if (!leave) leave = config.leave;

  let com = leave.split("[user]")
    .join(client.users.cache.get(member.id).username)
    .split("[inviter]")
    .join(client.users.cache.get(user).username)
    .split("[invites]")
    .join(db.get(`invites_${member.guild.id}_${user}.invites`))
    .split("[total]")
    .join(db.get(`invites_${member.guild.id}_${user}.regular`))
    .split("[leaves]")
    .join(db.get(`invites_${member.guild.id}_${user}.leaves`))
    .split("[jointimes]")
    .join(db.get(`invites_${member.guild.id}_${user}.joins`))



  member.guild.channels.cache.get(channel).send(com)
}
)

Object is Not a Function in firebase PhoneAuthentication

I am building a form where I have to login into the user by their phone number on CLICKING the send code button I got an error TypeError: Object(…) is not a function where it says that window is not a function can anybody solve my problem.
Error Image

Here is some of my code

import * as React from "react";
import { useState } from "react";
import Avatar from "@mui/material/Avatar";
import Button from "@mui/material/Button";
import ButtonGroup from "@mui/material/ButtonGroup";
import CssBaseline from "@mui/material/CssBaseline";
import TextField from "@mui/material/TextField";
import FormControlLabel from "@mui/material/FormControlLabel";
import Checkbox from "@mui/material/Checkbox";
import Link from "@mui/material/Link";
import Paper from "@mui/material/Paper";
import Box from "@mui/material/Box";
import Grid from "@mui/material/Grid";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import Typography from "@mui/material/Typography";
import { createTheme, ThemeProvider } from "@mui/material/styles";
import background from "../staticfiles/signin-background.jpg";
import "react-phone-input-2/lib/style.css";
import { auth, db, captcha } from "../config/Config";
import { RecaptchaVerifier } from "firebase/auth";
import { Link as RouterLink } from "react-router-dom";
import { useHistory } from "react-router-dom";

import socialMediaAuth from "../service/auth";

function Copyright(props) {
  return (
    <Typography
      variant="body2"
      color="text.secondary"
      align="center"
      {...props}
    >
      {"Copyright © "}
      <Link color="inherit" href="https://mui.com/">
        Your Website
      </Link>{" "}
      {new Date().getFullYear()}
      {"."}
    </Typography>
  );
}

const theme = createTheme();

export default function SignInUserPhone() {
  let history = useHistory();
  const [PhoneNumber, setPhoenNumber] = useState("");
  const [VerificationCode, setVerificationCode] = useState("");

  const [error, setError] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(PhoneNumber);

    console.log(error);
  };
  const handleSubmit2 = (e) => {
    e.preventDefault();
    console.log(VerificationCode);
  };

  const handleOnClick = async (provider) => {
    const res = await socialMediaAuth(provider);
    await db
      .collection("SignedUpUsersData")
      .doc(res.uid)
      .set({
        Email: res.email,
        Name: res.displayName,
      })
      .then(() => {
        history.push("/");
      })
      .catch((err) => setError(err.message));
  };

  const handleUserButton = (event) => {
    event.preventDefault();
    history.push("/signinuser");
  };

  const handleSellerButton = (event) => {
    event.preventDefault();
    history.push("/signinseller");
  };
  auth.languageCode = "it";
  const setUpCaptcha = () => {
    window.recaptchaVerifier = auth().RecaptchaVerifier("recaptcha-container", {
      size: "invisible",
      callback: (response) => {
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        console.log(response);
        console.log("Ok recapthca sloved");
        onSignInSubmit();
      },
    });
  };

  const onSignInSubmit = (e) => {
    e.preventDefault();
    setUpCaptcha();
    const phoneNumber = PhoneNumber;
    const appVerifier = window.recaptchaVerifier;

    auth()
      .signInWithPhoneNumber(PhoneNumber, appVerifier)
      .then((confirmationResult) => {
        // SMS sent. Prompt user to type the code from the message, then sign the
        // user in with confirmationResult.confirm(code).
        window.confirmationResult = confirmationResult;
        console.log(confirmationResult);
        // ...
      })
      .catch((error) => {
        // Error; SMS not sent
        // ...

        console.log(error.message);

        //( Or, if you haven't stored the widget ID:
      });
  };

  return (
    <ThemeProvider theme={theme}>
      <Grid container component="main" sx={{ height: "100vh" }}>
        <CssBaseline />
        <Grid
          item
          xs={false}
          sm={4}
          md={7}
          sx={{
            backgroundImage: `url(${background})`,
            backgroundRepeat: "no-repeat",
            backgroundColor: (t) =>
              t.palette.mode === "light"
                ? t.palette.grey[50]
                : t.palette.grey[900],
            backgroundSize: "cover",
            backgroundPosition: "center",
          }}
        />
        <Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
          <Box
            sx={{
              my: 8,
              mx: 4,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
            }}
          >
            <Avatar sx={{ m: 1, bgcolor: "secondary.main" }}>
              <LockOutlinedIcon />
            </Avatar>
            <Typography component="h1" variant="h5">
              Sign in With Phone Number
            </Typography>

            <Box
              sx={{
                my: 4,
                mx: 4,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <ButtonGroup size="large" disableElevation variant="contained">
                <Button onClick={handleSellerButton}>SELLER</Button>
                <Button onClick={handleUserButton}>USER</Button>
              </ButtonGroup>
            </Box>

            <Box
              component="form"
              noValidate
              onSubmit={onSignInSubmit}
              sx={{ mt: 1 }}
            >
              <TextField
                margin="normal"
                required
                fullWidth
                id="email"
                label="Phone Number"
                name="Phone"
                autoComplete="phoenumber"
                value={PhoneNumber}
                onChange={(phone) => setPhoenNumber(phone.target.value)}
              />
              <div id="recaptcha-container"></div>

              <Button
                type="submit"
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2 }}
                onSubmit={onSignInSubmit}
                id="sign-in-button"
              >
                Send Code
              </Button>

              <Grid container>
                <Grid item xs></Grid>
                <Grid item>
                  <Link
                    component={RouterLink}
                    to="/signup"
                    href="#"
                    variant="body2"
                  >
                    {"Don't have an account? Sign Up"}
                  </Link>
                </Grid>
              </Grid>
            </Box>
            {error && <div>{error}</div>}
            <Box
              component="form"
              noValidate
              onSubmit={handleSubmit2}
              sx={{ mt: 1 }}
            >
              <TextField
                margin="normal"
                required
                fullWidth
                id="email"
                label="Verification Code"
                name="Verification"
                autoComplete="Verification"
                value={VerificationCode}
                onChange={(verification) =>
                  setVerificationCode(verification.target.value)
                }
              />
              <Button
                type="submit"
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2 }}
              >
                Submit
              </Button>

              <Copyright sx={{ mt: 5 }} />
            </Box>
          </Box>
        </Grid>
      </Grid>
    </ThemeProvider>
  );
}

All the files are correctly exported from config js cause sign in with email and password and sign in with social media are working

res.send() creates TypeError: Converting circular structure to JSON

I know this error message has been asked before, but I don’t believe other solutions work for me.

I’m trying to build a backend express server to handle API calls for a React app. I wrote a getData() function to do this, used by an app.post() to send it to the front-end.

The error only pops up when using res.send(), e.g. my API calls work, just break when sending.

Here’s the relevant code:

const getData = async route => {
    const config = {
        headers: {
            'Authorization': `Bearer ${TOKEN}`,
            'Content-Type': 'application/json;charset=utf-8'
        }
    }

    let corrRoute = route[0] == '/' ? route : '/' + route
    return await axios(`${URL}${corrRoute}?api_key=${API_KEY}`, config)
}


app.post('/api', async (req, res) => {
    let { route } = req.body
    res.send(await getData(route))
})

If I replace the res.send at the end there with console.log it prints out perfectly fine. The error is being produced in the server’s index.js file, not in the React app.

Here is the full error text:

[server] (node:9680) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
[server]     --> starting at object with constructor 'ClientRequest'    
[server]     |     property 'socket' -> object with constructor 'TLSSocket'
[server]     --- property '_httpMessage' closes the circle
[server]     at JSON.stringify (<anonymous>)

Unable to complete freeCodeCamp challenge, despite code and DB connection being correct

I’ve been trying to complete the “Use model.findOne() to Return a Single Matching Document from Your Database” challenge under the MongoDB and Mongoose lessons on freeCodeCamp, but despite having the same code as the solution, the test fails.

I’ve double checked the formatting of my MongoDB URI in the .env, I’ve tried troubleshooting it as a CORS error, and I’ve even tried disabling my firewall and turning off adblockers / script blockers for freeCodeCamp, mongoDB, and Replit, but to no avail.

When I click the submission button to complete the challenge, the console immediately displays the POST request, but it doesn’t show up under the Network tab in DevTools, and after a varying number of seconds, [object Object] is printed to the console.

What can I do to resolve, or even debug this?

Thanks in advance for your time and consideration.

Edit: The function that specifically should be executing is findOneByFood.

myApp.js –

const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });

const personSchema = new Schema({
  name : { type: String, required: true },
  age : Number,
  favoriteFoods : [{ type: String, unique: true }]
});

let Person = mongoose.model('Person', personSchema);

const createAndSavePerson = (done) => {
  const johnCarmack = new Person({ name: "John Carmack", age: 51, favoriteFoods: ['iunno', 'Probably Pizza', 'I'm Not Googling It'] });
  johnCarmack.save((err, data) => {
  if (err) return done(err);
  done(null, data);
  });
};

const createManyPeople = (arrayOfPeople, done) => {
  Person.create(arrayOfPeople, (err, data) => {
    if (err) return done(err);
    done(null, data);
  })
};

const findPeopleByName = (personName, done) => {
  Person.find({ name: personName }, (err, data) => {
    if (err) return done(err);
    done(null, data);
  });
};

const findOneByFood = (food, done) => {
  Person.findOne({ favoriteFoods: food }, (err, data) => {
    if (err) return console.log(err);
    done(null, data);
  });
};

const findPersonById = (personId, done) => {
  done(null /*, data*/);
};

const findEditThenSave = (personId, done) => {
  const foodToAdd = "hamburger";

  done(null /*, data*/);
};

const findAndUpdate = (personName, done) => {
  const ageToSet = 20;

  done(null /*, data*/);
};

const removeById = (personId, done) => {
  done(null /*, data*/);
};

const removeManyPeople = (done) => {
  const nameToRemove = "Mary";

  done(null /*, data*/);
};

const queryChain = (done) => {
  const foodToSearch = "burrito";

  done(null /*, data*/);
};

/** **Well Done !!**
/* You completed these challenges, let's go celebrate !
 */

//----- **DO NOT EDIT BELOW THIS LINE** ----------------------------------

exports.PersonModel = Person;
exports.createAndSavePerson = createAndSavePerson;
exports.findPeopleByName = findPeopleByName;
exports.findOneByFood = findOneByFood;
exports.findPersonById = findPersonById;
exports.findEditThenSave = findEditThenSave;
exports.findAndUpdate = findAndUpdate;
exports.createManyPeople = createManyPeople;
exports.removeById = removeById;
exports.removeManyPeople = removeManyPeople;
exports.queryChain = queryChain;

server.js –

 * DO NOT EDIT THIS FILE
 * the verification process may break
 *******************************************/
const express = require("express");
const app = express();
let mongoose;
try {
  mongoose = require("mongoose");
} catch (e) {
  console.log(e);
}
const fs = require("fs");
const path = require("path");
const bodyParser = require("body-parser");
const router = express.Router();

const enableCORS = function (req, res, next) {
  if (!process.env.DISABLE_XORIGIN) {
    const allowedOrigins = ["https://www.freecodecamp.org"];
    const origin = req.headers.origin;
    if (!process.env.XORIGIN_RESTRICT || allowedOrigins.indexOf(origin) > -1) {
      console.log(req.headers.origin + ", " + req.method);
      res.set({
        "Access-Control-Allow-Origin": origin,
        "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
        "Access-Control-Allow-Headers":
          "Origin, X-Requested-With, Content-Type, Accept",
      });
    }
  }
  next();
};

// global setting for safety timeouts to handle possible
// wrong callbacks that will never be called
const TIMEOUT = 10000;

app.use(bodyParser.urlencoded({ extended: "false" }));
app.use(bodyParser.json());

app.get("/", function (req, res) {
  res.sendFile(path.join(__dirname, "views", "index.html"));
});

router.get("/file/*?", function (req, res, next) {
  if (req.params[0] === ".env") {
    return next({ status: 401, message: "ACCESS DENIED" });
  }
  fs.readFile(path.join(__dirname, req.params[0]), function (err, data) {
    if (err) {
      return next(err);
    }
    res.type("txt").send(data.toString());
  });
});

router.get("/is-mongoose-ok", function (req, res) {
  if (mongoose) {
    res.json({ isMongooseOk: !!mongoose.connection.readyState });
  } else {
    res.json({ isMongooseOk: false });
  }
});

const Person = require("./myApp.js").PersonModel;

router.use(function (req, res, next) {
  if (req.method !== "OPTIONS" && Person.modelName !== "Person") {
    return next({ message: "Person Model is not correct" });
  }
  next();
});

router.post("/mongoose-model", function (req, res, next) {
  // try to create a new instance based on their model
  // verify it's correctly defined in some way
  let p;
  p = new Person(req.body);
  res.json(p);
});

const createPerson = require("./myApp.js").createAndSavePerson;
router.get("/create-and-save-person", function (req, res, next) {
  // in case of incorrect function use wait timeout then respond
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  createPerson(function (err, data) {
    clearTimeout(t);
    if (err) {
      return next(err);
    }
    if (!data) {
      console.log("Missing `done()` argument");
      return next({ message: "Missing callback argument" });
    }
    Person.findById(data._id, function (err, pers) {
      if (err) {
        return next(err);
      }
      res.json(pers);
      pers.remove();
    });
  });
});

const createPeople = require("./myApp.js").createManyPeople;
router.post("/create-many-people", function (req, res, next) {
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    // in case of incorrect function use wait timeout then respond
    let t = setTimeout(() => {
      next({ message: "timeout" });
    }, TIMEOUT);
    createPeople(req.body, function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      Person.find({}, function (err, pers) {
        if (err) {
          return next(err);
        }
        res.json(pers);
        Person.remove().exec();
      });
    });
  });
});

const findByName = require("./myApp.js").findPeopleByName;
router.post("/find-all-by-name", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  Person.create(req.body, function (err, pers) {
    if (err) {
      return next(err);
    }
    findByName(pers.name, function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      res.json(data);
      Person.remove().exec();
    });
  });
});

const findByFood = require("./myApp.js").findOneByFood;
router.post("/find-one-by-food", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person(req.body);
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    findByFood(pers.favoriteFoods[0], function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      console.log(data);
      res.json(data);
      p.remove();
    });
  });
});

const findById = require("./myApp.js").findPersonById;
router.get("/find-by-id", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person({ name: "test", age: 0, favoriteFoods: ["none"] });
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    findById(pers._id, function (err, data) {
      clearTimeout(t);
      if (err) {
        return next(err);
      }
      if (!data) {
        console.log("Missing `done()` argument");
        return next({ message: "Missing callback argument" });
      }
      res.json(data);
      p.remove();
    });
  });
});

const findEdit = require("./myApp.js").findEditThenSave;
router.post("/find-edit-save", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person(req.body);
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    try {
      findEdit(pers._id, function (err, data) {
        clearTimeout(t);
        if (err) {
          return next(err);
        }
        if (!data) {
          console.log("Missing `done()` argument");
          return next({ message: "Missing callback argument" });
        }
        res.json(data);
        p.remove();
      });
    } catch (e) {
      console.log(e);
      return next(e);
    }
  });
});

const update = require("./myApp.js").findAndUpdate;
router.post("/find-one-update", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  let p = new Person(req.body);
  p.save(function (err, pers) {
    if (err) {
      return next(err);
    }
    try {
      update(pers.name, function (err, data) {
        clearTimeout(t);
        if (err) {
          return next(err);
        }
        if (!data) {
          console.log("Missing `done()` argument");
          return next({ message: "Missing callback argument" });
        }
        res.json(data);
        p.remove();
      });
    } catch (e) {
      console.log(e);
      return next(e);
    }
  });
});

const removeOne = require("./myApp.js").removeById;
router.post("/remove-one-person", function (req, res, next) {
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    let t = setTimeout(() => {
      next({ message: "timeout" });
    }, TIMEOUT);
    let p = new Person(req.body);
    p.save(function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        removeOne(pers._id, function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          console.log(data);
          Person.count(function (err, cnt) {
            if (err) {
              return next(err);
            }
            data = data.toObject();
            data.count = cnt;
            console.log(data);
            res.json(data);
          });
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

const removeMany = require("./myApp.js").removeManyPeople;
router.post("/remove-many-people", function (req, res, next) {
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    let t = setTimeout(() => {
      next({ message: "timeout" });
    }, TIMEOUT);
    Person.create(req.body, function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        removeMany(function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          Person.count(function (err, cnt) {
            if (err) {
              return next(err);
            }
            if (data.ok === undefined) {
              // for mongoose v4
              try {
                data = JSON.parse(data);
              } catch (e) {
                console.log(e);
                return next(e);
              }
            }
            res.json({
              n: data.n,
              count: cnt,
              ok: data.ok,
            });
          });
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

const chain = require("./myApp.js").queryChain;
router.post("/query-tools", function (req, res, next) {
  let t = setTimeout(() => {
    next({ message: "timeout" });
  }, TIMEOUT);
  Person.remove({}, function (err) {
    if (err) {
      return next(err);
    }
    Person.create(req.body, function (err, pers) {
      if (err) {
        return next(err);
      }
      try {
        chain(function (err, data) {
          clearTimeout(t);
          if (err) {
            return next(err);
          }
          if (!data) {
            console.log("Missing `done()` argument");
            return next({ message: "Missing callback argument" });
          }
          res.json(data);
        });
      } catch (e) {
        console.log(e);
        return next(e);
      }
    });
  });
});

app.use("/_api", enableCORS, router);

// Error handler
app.use(function (err, req, res, next) {
  if (err) {
    res
      .status(err.status || 500)
      .type("txt")
      .send(err.message || "SERVER ERROR");
  }
});

// Unmatched routes handler
app.use(function (req, res) {
  if (req.method.toLowerCase() === "options") {
    res.end();
  } else {
    res.status(404).type("txt").send("Not Found");
  }
});

const listener = app.listen(process.env.PORT || 3000, function () {
  console.log("Your app is listening on port " + listener.address().port);
});

/********************************************
 * DO NOT EDIT THIS FILE
 * the verification process may break
 *******************************************/

Timezone JS function

I am wanting to get this function to work to display the timezone in the footer of my webpage. As of now, when the webpage is loaded, the timezone does not appear in the footer of the webpage as intended.

This is what I have for JS script:

// This function displays the timezone.

function timezoneName() {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timezone);
document.getElementById("timezone").innerHTML = timezone;
}
timezoneName();

This is what I have for .html footer:

<footer>
<p id="timezone"></p>
</footer>

how to remove a classList when I select another element?

When I click on an ‘imposter’ I want it to become grey with some text as you can see in my CSS with the selector .imposter.voted. But when I click another imposter I want that one to appear grey and the previous one to appear like usual again.

When I try this.classList.remove("voted") it does not work and it just makes all the imposters I select grey. The class does not get removed. I don’t see where I went wrong.

imposters = document.querySelectorAll(".imposter");

for (let i = 0; i < imposters.length; i++) {
  imposters[i].addEventListener("click", function() {
    this.classList.add("voted");
  });
}
.imposter.voted {
  background-color: gray;
  position: relative;
  opacity: 0.7;
}

.imposter.voted::after {
  content: "I voted";
  position: absolute;
  top: 5px;
  right: 5px;
  display: inline-block;
  font-family: "Comic Sans Ms";
  color: red;
}

.imposters__voting {
  text-align: right;
}
<main class="dashboard">
  <h1>Who Is The Imposter?</h1>
  <div class="imposters">
    <div class="imposter">Baba</div>
    <div class="imposter">Baraki</div>
    <div class="imposter">Garfield</div>
    <div class="imposter">Erik</div>
    <div class="imposter">GreenBlood4</div>
    <div class="imposter">Easter</div>
  </div>
</main>

PNPM docker non-root user Permission Denied

I just found about pnpm today and it helped solve my issue with npm timing out on my installation which is amazing.
I’ve a problem with pnpm tho in the docker image.

Previously with just npm I had unprivileged user like so

FROM node:14.17.3-slim

# build args
ARG NPM_AUTH_TOKEN
ARG HOME=/home/app
ARG NPMRC_PATH=$HOME/.npmrc

# setup unprivileged user
RUN useradd -Umrd $HOME app
WORKDIR $HOME
USER app

# copy configuration
COPY --chown=app:app "bin" "bin"
COPY --chown=app:app "package.json" "package-lock.json" "webpack.config.js" ".babelrc" ./

RUN ./bin/write_npmrc && 
    npm ci --production=false

ENV NODE_ENV=development
VOLUME ["$HOME/config", "$HOME/log", "$HOME/src"]
CMD ["npm", "start"]
EXPOSE 9000

But if I switch to the pnpn I’m no longer able to proceed with building the image due to Permission Denied and I need to use root user.

FROM node:14.17.3-slim

# build args
ARG NPM_AUTH_TOKEN
ARG HOME=/home/app
ARG NPMRC_PATH=$HOME/.npmrc

RUN apt-get update && apt-get install -y curl 
 && rm -rf /var/lib/apt/lists/*
RUN curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm

WORKDIR $HOME

# copy configuration
COPY "bin" "bin"
COPY "package.json" "pnpm-lock.yaml" "webpack.config.js" ".babelrc" ./

RUN ./bin/write_npmrc && 
    pnpm install --frozen-lockfile

ENV NODE_ENV=development
VOLUME ["$HOME/config", "$HOME/log", "$HOME/src"]
CMD ["pnpm", "start"]
EXPOSE 9000

Is there a way so I can keep

# setup unprivileged user
    RUN useradd -Umrd $HOME app
    WORKDIR $HOME
    USER app

With pnpm instead?

Use fetch or axios to display html content of another page running the scripts

I want to use fetch or axios to download a html content of a page, this works fine but the javascript code inside the page does not run

here is what i’ve tried

document.getElementById('test').innerHTML=
await (await fetch('url')).text()

what i want is similar to this answer, but i want to get the page with the javascript inside processed instead of running a script.

Can I run a JS script from another using `fetch`?


My goal is to create a boostrapEmail template that i can send parameters and make it dynamic, using localstorage

https://bootstrapemail.com/docs/introduction