array.map not a function

When using array map method, the browser page is blank and in the console I receive an error:

array.map not a function

Although when I comment array.map before rendering the page and after page gets renderd I uncomment it and it works fine.

const movieDesc = useSelector((state) => state.movieDesc);
const [allVideo, setallVideo] = useState("");
const getAllVido = async () => {
try {
  const res = await axios.get(
    `https://api.themoviedb.org/3/${movieDesc.desc.media_type}/${movieDesc.desc.id}/videos?api_key=${process.env.REACT_APP_API_KEY}`
  );
  console.log(res.data);
  setallVideo(res.data.results);
} catch {
  console.log(Error);
}
};
useEffect(() => {
  getAllVido();
}, []);

JSX code:

<p className="movieDesc__trailer">All Video</p>
  {allVideo?.map((video) => (
    <>
      <p key={video.id}>{video.name}</p>
      <iframe
        key={video.id}
        className="movieDesc__trailerVideo"
        src={`https://www.youtube.com/embed/${video.key}`}
        title={video.name}
        frameborder="0"
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowfullscreen
      ></iframe>
    </>
  ))}

  <p className="movieDesc__wrap">Wrapping Up</p>

Storing wordle user gameplay

I am building a simple quiz game in JS/CSS. Curious about how wordle stores the streak statistics. Is it in the cookies?
Also, I want users to be able to access previous games and also their attempts. Is it possible to do it without having them create an account?

checking if a collection in indexeddb is empty

I’m trying to check if x is empty or has 30 entries, I wrote this however everytime I run it it doesn’t use the data saved in indexeddb [it adds entries [duplicate, already existing] how can I fix this?

let x = repo.getjuzs()
let y = Object.keys(x).length;
alert(typeof(y))
if (y < 30) {
    const juzs = await getJuzs();
    juzs.map(j => repo.addjuz(j))
    document.querySelector('#juz-DropDown').innerHTML = `
            ${juzs.map(j => `<option value="${j.id}">${j.juz_number}</option>`).join('n')}
        `;
    
}
const juzs = repo.getjuzs()
document.querySelector('#juz-DropDown').innerHTML = `
            ${juzs.map(j => `<option value="${j.id}">${j.juz_number}</option>`).join('n')}
        `;

how to cross section 2 arrays in javascript, by comparing id?

i have 2 arrays of objects with the same structure , each one of them came from database query, how i can map the cross section into a new array by comparing the ID value.

tempArray=[{city:london,subject:"testdata", id:7777},   {city:london,subject:"testdata", id:5555}]

tempArray1=[{city:london,subject:"testdata", id:8888},   {city:london,subject:"testdata", id:5555}]
     

im trying to get the result:

 newArray=[{city:london,subject:"testdata", id:5555}]

this is my try but i failed miserably

 let newArray=tempArray.map((x)=>{
                if (x.id== tempArray1.forEach((doc)=>{
                 console.log(doc.id);
                  return doc.id})) {return x
                  
                }
             
              }) 

convert from XMLHttpRequest to Fetch

How can I convert the following javascript based on XMLHttpRequest to Fetch?
This is the sample code provided by Trix-editor for uploading images from here
I want to migrate to Fetch for a few reasons:

  • I want to be consistent across my codebase and use fetch()
    for my other API calls.

  • I’m a newbie and read the XMLHttpRequest doc but don’t understand it. Fetch just seems more intuitive to me for some reason so another reason to convert this.

  • Plus, this code does not work for me but I don’t know how to
    troubleshoot. I have a Flask route that uploads the file (the one specified as HOST) but the tags aren’t being saved in Trix-editor.

    (function() {
    var HOST = “http://localhost:5000/_upload/”

    addEventListener(“trix-attachment-add”, function(event) {
    if (event.attachment.file) {
    uploadFileAttachment(event.attachment)
    }
    })

    function uploadFileAttachment(attachment) {
    uploadFile(attachment.file, setProgress, setAttributes)

     function setProgress(progress) {
       attachment.setUploadProgress(progress)
     }
    
     function setAttributes(attributes) {
       attachment.setAttributes(attributes)
     }
    

    }

    function uploadFile(file, progressCallback, successCallback) {
    var key = createStorageKey(file)
    var formData = createFormData(key, file)
    var xhr = new XMLHttpRequest()
    xhr.open(“POST”, HOST, true)

     xhr.upload.addEventListener("progress", function(event) {
       var progress = event.loaded / event.total * 100
       progressCallback(progress)
     })
    
     xhr.addEventListener("load", function(event) {
       if (xhr.status == 204) {
         var attributes = {
           url: HOST + key,
           href: HOST + key + "?content-disposition=attachment"
         }
         successCallback(attributes)
       }
     })
    
     xhr.send(formData)
    

    }

    function createStorageKey(file) {
    var date = new Date()
    var day = date.toISOString().slice(0,10)
    var name = date.getTime() + “-” + file.name
    return [ “tmp”, day, name ].join(“/”)
    }

    function createFormData(key, file) {
    var data = new FormData()
    data.append(“key”, key)
    data.append(“Content-Type”, file.type)
    data.append(“file”, file)
    return data
    }
    })();

Convert rads to degrees and return absolute value for 360

How do I convert rads to degrees and return absolute value for 360 degrees. That is, once it gets past 180 it continues to 359, then to 0.

The following returns positive degrees, but only in the 180 range.

console.log(Math.abs(rads * (180/Math.PI)));

The purpose for this is that I want to return numbers in a compass up to 360 degrees, and not show negative numbers.

Can we send un-encrypted media RTP by disabling fingerprint in the WebRTC offer / answer?

Attempting to implement an SFU, where all the WebRTC peers upload their unencrypted media streams to our customized server; so that they can be distributed to other peers in a loop without any decryption / re-encryption worries.
This is because, Haven’t found any source code to decrypt.

For that, I tried to generate an offer at JS side using createOffer() and before feeding it to setLocalDescription(), I removed the "a=fingerprint:sha-256 xx:YY..." from it. However, it gives an error:

DOMException: Failed to execute 'setLocalDescription' on 'RTCPeerConnection': Failed to set local offer sdp: Called with SDP without DTLS fingerprint.

There is an interface available called RTCDtlsFingerprint which might help in disabling fingerprint, but not sure how to use it.

Is there a way to disable fingerprint or DTLS-SRTP and hack it to send an unencrypted data?

Constructor makes an object of the first parameter with all the results

I’m trying to register an user and I use a constructor class for it, but when I put the parameters in the constructor and make the query, it takes the first parameter that I passed to the constructor and puts all the information as if it were an object of that parameter. Like this:
enter image description here

And when I try to put a parameter to be able to use it like this this.username = username, I meet with this

enter image description here

Here’s my code:

class User{
    constructor(user){
        this.username = user.username
        this.email = user.email
        this.birthday = user.birthday
        this.picture = user.picture
        this.password = user.password
    }
}

//////

async signUp(req,res){
        const newUser = new User(req.body)
        console.log(newUser)
        const result = await newUser.save()
        console.log(result)
        return res.redirect("/")
}

////

router.post("/signup", authcontroller.signUp)

How to select and manipulate the dynamically created html element with javascript?

I am pretty new to js, and I am building a color scheme generator as a solo project.
I am now stuck on select the html element that created dynamically.
I tried to select both labels and inputs element below, using document.getElementByClassName but it gives me that element I selected ‘undefined’

Click to copy!
`

I wanna select multiple labels and multiple inputs elements and add a clickEvent so that user can copy the resultColor code from both label and input

function renderColor(){

    //to store result of color scheme set object

      resultColorDivHtml = resultColorSchemeSet.map((resultColorItem) => {
        return `<div class="result-color" style="background-color: ${resultColorItem};"></div>`;
      }).join('')

      resultCodeDivHtml = resultColorSchemeSet
        .map((resultColor) => {
          return `
                    <label for='${resultColor}' class='copy-label'>Click to copy!</label>
                    <input class='result-code' id='${resultColor}' type="text" value='${resultColor}'/>`;
        })
        .join("");

        
      resultColorDiv.innerHTML = resultColorDivHtml;
      resultColorCodeDiv.innerHTML = resultCodeDivHtml;

}

Further issues with scores in simple JS game

I recently had an issue with a simple JS game, which I asked about here: Issue with negative scores in a simple JS game

It was fixed after I was advised to fix the else if statement. After that it worked fine.

I copied this game and swapped out the maths guessing part for a capital city guessing part, leaving everything else the same. The structure of the if/else if statements remains the same. However I am having the same issue again with the score not calculating correct, it starts increasing by more than 1x each time a question is answered.

The JS is:

//Initial values assigned
let score = 0
let countDown = 10

//Start Button Triggers this countdown function:
function startCountdown(seconds) {
  document.getElementById("start").setAttribute('disabled', '') //Disables Start button once the game starts
  let counter = seconds;
    
  const interval = setInterval(() => {
    document.getElementById("timer").innerHTML = Math.floor(counter);
    counter--;
      
    if (counter < 0 ) {
      clearInterval(interval);
      game()
      startCountdown(countDown) //this function with "countDown" argument passed in starts a new countdown
    }
  }, 1000);
}

//This function triggers a new question
function game(){
  
  //Decreases the countdown time as the score gets higher:
  if (score > 5 && score < 11){
    countDown = 10-score/2
    
  }
  
 //This block is game questions and answers:
  
  const countries = [
    {ID:1,Country:"New Zealand",Capital:"Wellington"}, 
    {ID:2,Country:"Belarus",Capital:"Minsk"}, 
    {ID:3,Country:"Japan",Capital:"Tokyo"},
    {ID:4,Country:"Philippines",Capital:"Manila"},
    {ID:5,Country:"Mongolia",Capital:"Ulaanbaatar"},
    {ID:6,Country:"Switzerland",Capital:"Bern"}


    ];
  
    let random = Math.floor(Math.random() * countries.length);
    let random2 = Math.floor(Math.random() * countries.length);
    let random3 = Math.floor(Math.random() * countries.length);

    let chosen = countries[random];
    document.getElementById("challenge").innerHTML = `What is the capital city of<b>${chosen.Country}</b> ?`
  
  
 //let answer1 = Math.floor(Math.random()*500)
 //let answer2 = Math.floor(Math.random()*500)
 //document.getElementById("challenge").innerHTML = `What is <b>${answer1}</b> plus <b>${answer2}</b>?`
     let number1 = countries[random2].Capital;
     let number2 = chosen.Capital;
     let number3 = countries[random3].Capital;
     let gameNums = [number1, number2,number3]
     shuffle(gameNums)
  document.getElementById("button1").innerHTML = gameNums[0]
  document.getElementById("button2").innerHTML = gameNums[1]
  document.getElementById("button3").innerHTML = gameNums[2]
  
  //This function determines which answer is correct and incorrect:
  function handleClick(event) {

  if (event.target.tagName !== "BUTTON") {
    return;
  }

  let buttonValue = event.target.innerText;
  
    //Correct Answer:
    if (buttonValue == number2){
      document.querySelector("#result").innerText = "Correct!";
      document.getElementById("result").style.color = "green";
      score++
      document.getElementById("score").innerHTML = `Score = ${score}`
      game()
      }
    
    //Incorrect Answer:
    else if(buttonValue == number1 || buttonValue == number3){
       document.querySelector("#result").innerText = "Incorrect!";
       document.getElementById("result").style.color = "red";
       score--
          //This stops the score going below zero:
          if (score < 0){
          score = 0
          }
      document.getElementById("score").innerHTML = `Score = ${score}`
      game()
       }
    
    
}
  

//Listens for button clicks
document.querySelector(".buttons").addEventListener("click", handleClick);

}
  

//function for shuffling the array

function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle...
  while (currentIndex != 0) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}

Codepen: https://codepen.io/tmnsoon/pen/yLpOmeX?editors=1010

Not sure why this is?

Thanks!

I am making a prototype e-commerce website as a project, how do I specifically just show an authenticated user’s orders?

As the title says I am a beginner learner who now got into learning the MERN stack. I am now currently using Node.js and Express for the server and about to create the client side in React.
My problems are I don’t know how to make all users’ orders appear for the admin, and how to make all the user’s checkouts appear to them but not the admin?

See the following photo on how a user’s orders reflect on the database (MongoDB). I test using Postman. POSTMAN PHOTO

See also my code on my routes and controllers on how a user checkouts an item.

CONTROLLERS

//USER CHECKOUT
module.exports.co = async (buy) => {
    const {userId, productId} = buy

    const buying = await User.findById(userId).then(result => {result.order.push({productId: productId})
    
    return result.save().then(user => user ? true: false)
})

    const bought = await Product.findById(productId).then(result => {
        result.checkOut.push({userId: userId})
        
        return result.save().then(product => product ? true : false)
    })

    if(buying && bought) {
        return 'Item checked out.'
    } else {
        return 'Item not checked out.'
    }

}

ROUTE

//User check-out
router.put('/:_id/check-out', verify, async (req, res) => {
    const user = decode(req.headers.authorization).isAdmin
    const buy = {
        userId: decode(req.headers.authorization).id,
        productId: req.body.productId
    }
    if(user == false){
    try{
        await co(buy).then(result => res.send(result))
    }catch(err){
        res.status(500).json(err)
    }
}else {
    res.send(`Only registered users can purchase items.`)
}
})

For event.target in onclick – “Uncaught TypeError TypeError: Cannot set properties of undefined (setting ‘value’)”

I’m trying to have my html call a javascript function onclick in which the function itself references the event that called it, but I keep getting this error:

Uncaught TypeError TypeError: Cannot set properties of undefined (setting 'value')
    at play (c:UsersC2RanDesktopPracticeapp.js:5:16)
    at onclick (c:UsersC2RanDesktopPracticeindex.html:24:68)

Here’s my html:

<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="app.js" defer></script>
</head> 
<body>
    <input type="button" value="X" id="turn" onclick="play(this);">
</body>
</html>

Here’s my javascript:

var turn = "X"

function play(event) {
    var cell = event.target;
    cell.value = turn;
    console.log(turn);
    if(turn == "X")
    {
        turn = "O"
    }
    else 
    {
        turn = "X"
    }
}

Is there something I’m missing? Why is it saying value is undefined? Is it not getting the event correctly? Or does onclick not count as an event? I also tried event.currentTarget instead

Where to start with a simple banking app? [closed]

I’m working through a course on JavaScript currently and honestly I’m having a pretty difficult time with it. If anyone has any resources they could recommend for learning, I’d appreciate it!

I’m trying to make a simple banking app with these requirements:

  • The user should see a prompt so they can type which action to perform.

  • The user will have a list of 4 actions to choose from.

  • Enter Q to quit (immediately quits the program).

  • Enter W to withdraw.

    • The user will be prompted again to enter an amount to withdraw. After withdrawing money,
      they should be able to type another option.
  • Enter D to deposit.

    • The user will be prompted again to enter an amount to deposit. After depositing money,
      they should be able to type another option.
  • Enter B to view balance.

    • The user will see their balance. Afterwards, they should be able to type another option.
  • The balance should update after any Withdrawal or Deposit transactions.

  • The program will loop asking for input until the user enters Q.

Here’s my basic HTML for a very simple site

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Welcome!</h1>
    <button onclick="start()">Click here to get started.</button>
    <script src="scripts.js"></script>
  </body>
</html>

And here’s as far as I’ve been able to get with the JS…

function start() {
  let input = prompt('What would you like to do?');

  if input = 'w' {
    alert('Withdraw');
  } else () {

  }
}

And I know that’s probably not even the direction I need to be going. I’m honestly stuck because I don’t really know where to start. Any and all advice is much appreciated, TIA!!

is there any way to save the value of onChange?

I’m having a question about onChange, so I was trying to pick up and send a value from my onChange to (”http://localhost:3000/search”), but when I press the (Enter) key it enters the page but ends up deleting the values of my onChange coming back undefined, is there any way to save my onChange and send to another page? without retone me undefined

My code:

function handleKeyPress(event: any) {
        if(event.keyCode === 13){
          open('http://localhost:3000/search')
        }
      }

    function search(e: any) {
    
        axios.get("http://localhost:3001/search", {params: {q: e.target.value}})
    
    }
    
    return(
        <>
            <div className={styles.Header}>

                <input name='q' type="text" placeholder='Buscar' onChange={(e)=>search(e)} onKeyDown={(e)=>handleKeyPress(e)}/>

                <div></div>
            </div>
        </>
    )

How do I efficiently create this multi button sound program in p5js

I’m trying to create a binaural audio sound demo player in p5js. It basically plays different sounds close, far, up, down, right, left, as if you were in a room. I’m new to p5js and have been struggling to create 8 circular buttons, arranged in a circle, that all play and pause various sounds. These buttons should change color and I am not sure why I’m having so much trouble but help is appreciated. The issue I’m having, so other people can be helped too, is how do I create multiple object buttons that change color and coordinate sound and text with each one? I tried using an array and constructor but it didn’t work. Thank you 🙂

https://editor.p5js.org/sheepblazer/sketches/TbRI7EmAH

I just attached the link to my editor as I thought it would be easier.