HTML Form submit for Radio Buttons

I have a basic HTML form that takes input from the user about his age, gender, dob, email and contact number. I save it into the local storage as employeeData by making it an object in an array. [{},{},{}]. I also add a User_id that is calculated by a random function generator and display it using the Javascript. An example is mentioned below.

[
    {
        "U_Id": "1a9f1268-9c74-4cfb-971c-f595cb4a40e1",
        "Name": "dsgfdsfds",
        "Gender": "Male",
        "Dob": "2022-02-04",
        "Email": "[email protected]",
        "Tel": "9958111111",
        "Hobbies": [
            "Coding"
        ]
    },
    {
        "U_Id": "d7e5b305-4604-4831-b168-96136a7b4ea5",
        "Name": "dghdghdhddh",
        "Gender": "Male",
        "Dob": "2022-02-04",
        "Email": "[email protected]",
        "Tel": "8989092345",
        "Hobbies": [
            "Coding",
            "Gaming"
        ]
    }
]

I create the object to store using const formData = new FormData(form);.

Now when I am fetching the data to display it back into the form, I am using the following function –

const empIndex = employeeData[index];
    const form = document.getElementById("form");

    for(let i=0;i<form.length;i++){
        console.log(form.elements[i])
        console.log(empIndex[keys[i]]);
        
        form.elements[i].value = empIndex[keys[i]];
    }
    const gender = empIndex.Gender;
    const hobbies = empIndex.Hobbies;
    form.elements[0].value = empIndex.Name;

But the issue is, the radio buttons are treated as 2 different entities and not as 1, which is why I have to individually set the name as Name and what happens is shown below-
This is how the console looks after the logs

I need to know why does the HTML not deals the radio buttons as a group and a single entity, but rather makes it seperate entities, forcing me to input values with the loop into all the form elements, meanwhile I have created a group for a reason to be able to treat it as a single entity, just like an array. An array is a group of entities, but the HTML radio button group is not a group? Anyway to go about it?

console.log("i am inside the script");

var incorrect = true;

function uuidv4() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );
}

function namechecker(name) {
  if (name == "" || name.length < 5 || name.length > 45) {
    document.getElementById("namehidden").style.display = "contents";
  } else {
    document.getElementById("namehidden").style.display = "none";
    incorrect = false;
  }
}

function dobChecker(dob) {
  if (!dob) {
    document.getElementById("dobhidden").style.display = "contents";
  } else {
    document.getElementById("dobhidden").style.display = "none";
    incorrect = false;
  }
}

function emailChecker(email) {
  const emailRegex =
    /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
  if (!(email && emailRegex.test(email))) {
    document.getElementById("emailhidden").style.display = "contents";
    incorrect = true;
  } else {
    document.getElementById("emailhidden").style.display = "none";
    incorrect = false;
  }
}

function phChecker(phone) {
  const phRegex = /^[6-9]d{9}$/;
  if (!phRegex.test(phone)) {
    console.log("Phone number is incorrect");
    document.getElementById("telhidden").style.display = "contents";
    incorrect = true;
  } else {
    document.getElementById("telhidden").style.display = "none";
    incorrect = false;
  }
}

function incorrectForm(name, dob, email, tel) {
  console.log(incorrect);
  namechecker(name);
  dobChecker(dob);
  emailChecker(email);
  phChecker(tel);
  if (!incorrect) return false;
  else return true;
}

function Init(form) {
  const formData = new FormData(form);
  const name = formData.get("name");
  const dob = formData.get("dob");
  const gender = formData.get("gender");
  const email = formData.get("email");
  const tel = formData.get("tel");
  const markedCheckbox = document.getElementsByName("hobbies");
  const hobbies = [];
  for (var checkbox of markedCheckbox) {
    if (checkbox.checked) {
      hobbies.push(checkbox.value);
    }
  }
  if (incorrectForm(name, dob, email, tel)) {
    console.log(
      "The form is incorrect. Kindly check and input correct entries."
    );
    alert("The Form is Incorrect. Kindly check the values and fill it correctly.")
  } else {
    return {
      U_Id: uuidv4(),
      Name: name,
      Gender: gender,
      Dob: dob,
      Email: email,
      Tel: tel,
      Hobbies: hobbies,
    };
  }
}

const but = document.getElementById("button");
console.log(but);
but.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("i clicked the button");
  const f = document.getElementById("form");
  const object = Init(f);
  if (object) {
    if (!localStorage.getItem("employeeData")) {
      localStorage.setItem("employeeData", JSON.stringify([object]));
    } else {
      const existing = JSON.parse(localStorage.getItem("employeeData"));
      existing.push(object);
      localStorage.setItem("employeeData", JSON.stringify(existing));
    }
    console.log(localStorage.getItem("employeeData"));
  }
// calling another script from the button if the form is correct.
  if (!incorrect) {
    console.log("hi i am in basic!");

var tdStyle = "border:1px solid green;min-width:110px;";

const table = document.createElement("table");
table.setAttribute("style", "table-layout: fixed; width:max-content");

const tr = document.createElement("tr");
const employeeData = JSON.parse(localStorage.getItem("employeeData"));

console.log(employeeData);

if (employeeData){
const keys = Object.keys(employeeData[0]);

for (let i = 0; i < keys.length; i++) {
  const th = document.createElement("th");
  th.innerText = keys[i];
  th.setAttribute("style", tdStyle);
  tr.appendChild(th);
}

const action = document.createElement("th");
action.innerText = "Actions";
action.setAttribute("style", tdStyle);
tr.appendChild(action);
const thead = document.createElement("thead");
thead.appendChild(tr);
table.appendChild(thead);

const tbody = document.createElement("tbody");

function btnCreator(index) {
  const buttontd = document.createElement("td");
  const editBtn = document.createElement("button");
  editBtn.setAttribute("id" , "edit" + index);
  editBtn.innerText = "Edit";
  editBtn.setAttribute("style","margin-inline-end:10px");
  buttontd.setAttribute("style", tdStyle);
  const delBtn = document.createElement("button");
  delBtn.setAttribute("id", "delete" + index);
  delBtn.innerText = "Delete";
  editBtn.addEventListener("click", ()=>editListener(index));
  buttontd.appendChild(editBtn);
  buttontd.appendChild(delBtn);
  return buttontd;
}

function editListener(index){
    const empIndex = employeeData[index];
    const form = document.getElementById("form");

    for(let i=0;i<form.length;i++){
        console.log(form.elements[i])
        console.log(empIndex[keys[i]]);
        
        form.elements[i].value = empIndex[keys[i]];
    }
    const gender = empIndex.Gender;
    const hobbies = empIndex.Hobbies;
    form.elements[0].value = empIndex.Name;
    document.getElementById("chkbx1").checked = false;
    document.getElementById("chkbx2").checked = false;
    document.getElementById("chkbx3").checked = false;
    document.getElementById("rdbox1").checked = true;
    document.getElementById("rdbox2").checked = false;

    if (gender =="Female"){
        document.getElementById("rdbox1").checked = false;
        document.getElementById("rdbox2").checked = true;
    }

    hobbies.forEach((element)=>{
        switch (element){
            case "Gaming":
                document.getElementById("chkbx1").checked = true;
                break;
            case "Coding":
                document.getElementById("chkbx2").checked = true;
                break;
            case "Music":
                document.getElementById("chkbx3").checked = true;
                break;
            default:
            break;
                }
})
}

employeeData.forEach(function (item, index, arr) {
  const tr2 = document.createElement("tr");
  for (let i in item) {
    const td = document.createElement("td");
    td.innerText = item[i];
    td.setAttribute("style", "border:1px solid green; width:100%");
    tr2.appendChild(td);
  }
  tr2.appendChild(btnCreator(index));
  tbody.appendChild(tr2);
  table.appendChild(tbody);
});

const basicdiv = document.getElementsByClassName("basic")[0];

basicdiv.appendChild(table);}
else{

}
});
body{
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.top-div{
    display: flex;
    margin-top: 200px;
    font-size: larger;
    font-weight: bold;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 100%;
}

.mid-div{
  display: flex;
  flex-direction: column;
    background-color: #1282cc;
    color: black;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    width: 75%;
}

.bot-div{
  background-color: white;
  border: solid thin #1282cc;
  border-radius: 4px;
  padding-bottom: 2%;
}

form{
  width: 100%;
  display: flex;
  flex-direction: column;
}
.namelabel{
  margin-top: 10px;
}

.col-25 {
  float: left;
  text-align: right;
  width: 22%;
  margin-top: 6px;
}

.col-75 {
  float: right;
  width: 73%;
  margin-right: 2%;
}

.required{
  color: red;
}


.dob ,.tel,.email{
  width: 100%;
}


.vertical{
  margin: 0 2.5% 0 0;
}

#button{
  background-color: #1282cc;
  color: white;
  margin-top: 5%;
  padding: 1% 2%;
  border: #1282cc solid thin;
  border-radius: 4px ;
}

span.items{
  color:black;
  padding-left: 0;
}

div span{
    color: white;
    font-size: medium;
    font-weight: lighter;
    padding:15px;

}

* {
    box-sizing: border-box;
  }
  
  input[type=text] {
    width: 100%;
    height: 25px;
    border: 1px solid #ccc;
    margin: 32px 12px 12px 0;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
  }

  input[type=radio]{
      margin: 23px 12px 12px 0;
  }

  input[type=date] {
    margin: 20px 12px 12px 0;
    border: 1px solid #ccc;
    height: 25px;
  }

  input[type=email] {
    margin: 23px 12px 12px 0;
    border: 1px solid #ccc;
    height: 25px;
  }

  input[type=tel]{
    margin: 23px 12px 12px 0;
    border: 1px solid #ccc;
    height: 25px;
  }
  
  label {
    padding: 12px 12px 12px 0;
    display: inline-block;
  }
  
.hidden{
  font-size: small;
  color: red;
  display: none;
}

.container {
    background-color: white;
    padding: 20px;
    border: blue 1px solid;
  }
  
  /* Clear floats after the columns */
  .row:after {
    content: "";
    display: table;
    clear: both;
  }

  @media screen and (max-width:840px) {
 
    .parent{
      display: flex;
      flex-direction: column;
    }

    .col-75{
      margin: 0;
      margin-left: 5%;
    }
    
    .col-25{
      width: 100%;
      margin: 0%;
      padding: 12px;
      text-align: left;
    }

    input[type=text] {
      margin: 10px 12px 12px 0;
    }

    input[type=email] {
      margin: 10px 12px 12px 0;
    }
  
    input[type=tel]{
      margin: 10px 12px 12px 0;
    }

    input[type=radio]{
      margin: 5px 5px 0 0;
  }

  .mf{
    display: flex;
  }
  }

  /* Adding styling for basic table */

  .basic{
    display: flex;
    flex-direction: row;
    width: 100%;
    overflow-x: auto;
  }
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" href="style.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>Employee Data</title>
  <script src="basic.js" defer></script>
</head>

<body>
  <div class="top-div">
    <h2>Employee</h2>
    <div class="mid-div">
      <span>Add Employee</span>
      <div class="bot-div">
        <form action="" id="form">
          <div class="parent">
            <div class="col-25">
              <label class="namelabel"> Name:</label>
            </div>
            <div class="col-75">
              <input name="name" type="text" maxlength="45" minlength="5" placeholder="Your Name" />
              <label class="hidden" id="namehidden">This field is required</label>
            </div>
          </div>
          <div class="parent">
            <div class="col-25">
              <label> Gender:</label>
            </div>
            <div class="col-75 mf">
              <div>
                <input type="radio" class="radio" name="gender" value="Male" id="rdbox1" checked /><span class="items">Male</span>
              </div>
              <div><input type="radio" class="radio" name="gender" value="Female" id="rdbox2"/><span class="items">Female</span>
              </div>
            </div>
          </div>
          <div class="parent">
            <div class="col-25">
              <label> Date of Birth:</label>
            </div>
            <div class="col-75">
              <input type="date" name="dob" class="dob" /><br>
              <label class="hidden visible" id="dobhidden">This field is required</label>
            </div>
          </div>
          <div class="parent">
            <div class="col-25">
              <label> Email:</label>
            </div>
            <div class="col-75">
              <input type="email" placeholder="Enter Email" name="email" class="email" />
              <br>
              <label class="hidden" id="emailhidden">This field is required</label>
            </div>
          </div>
          <div class="parent">
            <div class="col-25">
              <label> Phone:</label>
            </div>
            <div class="col-75">
              <input type="tel" placeholder="Enter phone" name="tel" class="tel" />
              <br>
              <label class="hidden" id="telhidden">This field is incorrect</label>
            </div>
          </div>
          <div class="parent">
            <div class="col-25">
              <label class="padding"> Hobbies:</label>
            </div>
            <div class="col-75 vertical" name="hobbies">
              <input class="chkbox" type="checkbox" name="hobbies" value="Gaming" id="chkbx1" /><span
                class="items">Gaming</span> <br>
              <input class="chkbox" type="checkbox" name="hobbies" value="Coding" id="chkbx2" /><span
                class="items">Coding</span> <br>
              <input class="chkbox" type="checkbox" name="hobbies" value="Music" id="chkbx3" /><span
                class="items">Music</span> <br>
            </div>
          </div>
          <div>
            <div class="col-75">
              <button type="submit" id="button">Submit</button>
            </div>
          </div>
        </form>
      </div>
    </div>
    <h2>Basic</h2>
    <div class="mid-div">
      <span>Add Employee</span>
      <div class="bot-div basic">
      </div>
    </div>
    <h2>Advanced</h2>
    <div class="mid-div">
      <span>Add Employee</span>
      <div class="bot-div">
        </div>
        </div>

  </div>
  </div>
</body>
<script src="script.js"></script>

</html>

Node Js pass the role as a string to the JWT verification function

the JWT verification function accepts the req, res and next as its params. I need to pass an additional string ‘Admin’ so that only admin users may access this API

My jwtVerification.js code:

module.exports = async function (req, res, next) { //I need to be able to add role to this call
    try {       
        const token = req.header("Authorization");

        if (!token) return res.status(401).send('Invalid access token.');

        const _token = token.substring(7, token.length);

        const decoded = jwt.verify(_token, process.env.JWT_PRIVATE_KEY)

        const user = await prisma.user.findFirst({ where: { id: decoded.id } });

        if (!user) return res.status(401).send('Invalid access token.');
     
        //I need to be able to read the role so that I can do the following verifications
        //if(!role) next();
        //else{
        //   if(user.role !== role || decode.role !== role) return res.status(403).send('Forbidden!')
        //   else next();
        //}
        next();

    } catch (error) {
        res.status(401).send(error.message);
    }
};

finally, the API call itself:
//use verifyJWT(‘Admin’) for example

router.post('/test', verifyJWT, async (req, res) => {
    res.send('hi');
})

How to make JS read the contents of a local text file

I know using JS to read the contents of a .txt is possible.

For example, I have a text file code.txt which contains

Abc
Ghi
123466
bored
idk

And I have index.js. I would like to use the contents of code.txt to create an array into index.js.

So, in that example, I would like an array like this to appear in index.js.

const entcode = [
  "Abc",
  "Ghi",
  "123466",
  "bored",
  "idk",
]

Is there a way to do that?

using flatmap to separate array with comma

I have the following array:

[
["Polymeric", "Vehicle Graphics (Basic)"],
["Cast", "Vehicle Graphics (Part Wrap), Vehicle Graphics (Full Wrap)"],
["Polymeric", "Vehicle Graphics (Part Wrap)"]
]

I need this:

[
["Polymeric", "Vehicle Graphics (Basic)"],
["Cast", "Vehicle Graphics (Part Wrap)"],
["Cast", "Vehicle Graphics (Full Wrap)"],
["Polymeric", "Vehicle Graphics (Part Wrap)"]
]

Here’s my code:

const source = [ 
  ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Basic)"],
  ["Cast", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap), Vehicle Graphics (Full Wrap)"],
  ["Polymeric", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, "Vehicle Graphics (Part Wrap)"]
];


source.flatMap(([key, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11, value12, value13, value14, value15, value16]) => { 

  const values = value16.split(', ') 

  var hjk = values.map(singleValue => [key, singleValue])
  console.log(hjk);
})

Here’s a jsfiddle of it working.

Is there a better way to do this? Putting value1, value2 etc seems silly.

How to trigger the Google Play login from React Native IAP

Is it possible to trigger the Google account sign-in dialogue from within a React Native app?

I have found while using IAPHub that you cannot even list products for sale if the user is not signed in on their Android device – because it seems to need to talk to the Play store with credentials.

Perhaps it’s an edge case, as most people would be always signed into their Google account if they use an Android device? But I felt like I wanted to be able to provide a nicer UX to show the login dialogue.

I’ve looked in the IAPHub docs and the repo docs the underlying https://github.com/dooboolab/react-native-iap but there doesn’t seem to be a direct interface to test if the user is logged in nor force a login. This makes me wonder if I’m looking in the wrong place.

I can see there’s a URL method like from https://stackoverflow.com/a/11753070/209288 but I was looking more for an in-app API.

Javascript – map is not a function

I’m having an odd issue. So I’m using fetch api to get some static data from an api endpoint to get some data. When I then try to map over the data it tells me map is not a function. So I’m making this in react. Also I haven’t used fetch too much so maybe I’m missing something easy.

Here is the fetchData code where I get the data no problem and then using setScanData(resData) for some state.

const fetchData = async () => {
  const res = await fetch(baseURL + apiAddOn);
  const resData = await res.json();
  setScanData(resData)
}

Here is how the resData comes back.

[
    {
        "teamName": "Team 1",
        "date": "2021-01-19",
        "tasksAWeek": 14
    },
    {
        "teamName": "Team 2",
        "date": "2021-01-19",
        "tasksAWeek": 21
    },
    {
        "teamName": "Team 3",
        "date": "2021-01-19",
        "tasksAWeek": 36
    }
]

And then here is how I try to map over the data and where is gives me the map is not a function error.

 {scanData.map((data) => {
        <div key={`${data.teamName}-${data.date}`}>
            <p>Team Name: {data.teamName}</p>
            <p>Date: {data.date}</p>
            <p>Scans a Week: {data.scansAWeek}</p>
            <p>Total Scans: {data.totalScans}</p>
        </div>
    })}

But ye so I’m not too sure where I’m going wrong with this. Any help would be useful.

how to update attributes of an object from user input?

(i am new to JS and i am facing a problem with getting user input in one of the functions)

i am writing a code where i have three classes (book, donor, bookCatalog)

class ‘book’ and ‘donor’ have only constructors while ‘bookCatalog’ have some functions like addbook(), addDonor() etc.

in one of the functions (in bookCatalog) i’m supposed to change the donor’s information, the function receives the donor id then search in a list of donors with that id and updates the donor attributes (like name,phone etc.)

i am supposed to test these methods in a new file but the problem is i dont know how to get the input from the user
i tried using prompt but i got an error “prompt is not defined”

Q. should the prompt be in the test file or inside ‘updateDonor’ function?

class bookCatalog:

export class BookCatalog{
    constructor(books, donors) {
        this.books = []
        this.donors = []
    }

updateDonor(donorId){
        const Id = prompt("enter donor ID: ")
        const firstname = prompt("enter first name: ")
        const lastname = prompt("enter lastname: ")
        const phone =  prompt("enter phone number: ")
        const street = prompt("enter street: ")
        const city = prompt("enter city: ")
        const email = prompt("enter email: ")
        const password = prompt("enter password: ")

        this.donors = this.donors.map(d =>{
            if(d.donorId === donorId){
                return {...d,
                    donorId: Id,
                    firstname: firstname,
                    lastname: lastname,
                    phone: phone,
                    street: street,
                    city: city,
                    email: email,
                    password: password
                }
            }
            return d
        })
    }
}

test file:

import {BookCatalog} from "./BookCatalog.js";
import {Donor} from "./Donor.js";

let catalog = new BookCatalog();
let donor1 = new Donor(0.1,"alex","A",726836,"st","chicago","[email protected]","123456")
catalog.addDonor(donor1)

console.log("donor 1 information after updating: ")
console.log(catalog.updateDonor(0.1))


How to set first value in “useState” function to true or false with “useEffect” function React

I am running into a problem with my current code. The code below is supposed to grab a JSON response from my backend and set “data” in the useState function to true or false based on the backend’s response. The issue I am having is that when I click on my button to redirect me to the page it must first go through this protected route in my react router. So it will run this script but the value of ‘data’ never changes. However, my console.log will output the correct boolean based on the JSON response sent from the backend. I am confused on how I can actually grab my JSON response on page load and set it to ‘data’ with useEffect? From my understanding, useEffect will only update my useState ‘data’ when the DOM re-renders.

In short, I want data to = true on page render by checking the JSON response from my backend using axios and if it is true I want to be redirected to the outlet.

I appreciate any help thanks.

 const useAuth = () => {
    
      const [data, setData] = useState(false);
    
      useEffect(() => {
        const fetchAuthData = async () => {
          await axios.get('http://localhost:5000/auth')
            .then(resp => {
              console.log(resp.data)
              setData(resp.data);
            })
            .catch(err => {
              console.log(err);
              setData(false)
            });
    
    
        };
    
        fetchAuthData()
      }, []);
    
      console.log(data)
      // Logic to check if backEndResponse is true or false
      if (data === true) {
        const authorized = { loggedIn: true }
        return authorized && authorized.loggedIn;
      } else {
        const authorized = { loggedIn: false }
        return authorized && authorized.loggedIn;
      }
    
    };
    
    
    const ProtectedRoutes = () => {
      const isAuth = useAuth();
      return isAuth ? <Outlet/> : <Navigate to="/login" />;
    }

How get data from component in another component?

I’m trying to pass data to the callback function, but for some reason it breaks everything and I always get the timer by zeros:

const [timerData, setTimerData] = useState({
    seconds: 0
    minutes: 0
    hours: 0
  });

  const callBackTimer = data => setTimerData(data);

  useEffect(() => {
    console log(timerData);
  },[timerData])

  const Timer = ({callback, data}) => {
    const [seconds, setSeconds] = useState(data.seconds);
    const [minutes, setMinutes] = useState(data.minutes);
    const [hours, setHours] = useState(data.hours);
    const [isActive, setIsActive] = useState(clients.length > 1);

    let toggle = () => {
      setIsActive(!isActive)
    }

    let reset = () => {
      setSeconds(0);
      setIsActive(false);
    }

    useEffect(() => {
      let interval = null;
      if (isActive) {
        interval = setInterval(() => {
          if(seconds < 60) setSeconds(seconds => seconds + 1);
          else {
            setSeconds(0);
            if(minutes < 60) setMinutes(minutes => minutes + 1);
            else {
              setMinutes(0);
              setHours(hours => hours + 1);
            }
          }
          console.log({hours, minutes, seconds});
          callback({hours, minutes, seconds});
        }, 1000);
      } else if (!isActive && seconds !== 0) {
        clearInterval(interval);
      }
      return() => clearInterval(interval);
    }, [isActive, seconds, minutes, hours, timerData]);

    return(
        <div className={'timer'}>
          <h1>{seconds}</h1>
          <h1>{minutes}</h1>
          <h1>{hours}</h1>
        </div>
    )
  }

My callback function not working and timer not updated.

I call the timer like this:

<Timer callback={callBackTimer} data={timerData}/>

Please tell me what I did wrong. Thanks.

My project run properly in my c-drive. but copy this project file to another drive . When try to run its give this error. in c drive it worked good

./node_modules/@pmmmwh/react-refresh-webpack-plugin/client/ReactRefreshEntry.js
Error: [BABEL] F:Programming herop-hero course-(Main-course)milestone-12( doctor portal project)module-69-74(final project)doctor-portal-client-sitenode_modules@pmmmwhreact-refresh-webpack-pluginclientReactRefreshEntry.js: Cannot find module ‘F:Programming herop-hero course-(Main-course)milestone-12( doctor portal project)module-69-74(final project)doctor-portal-client-sitenode_modulesbabel-preset-react-appnode_modules@babelplugin-proposal-nullish-coalescing-operatorlibindex.js’. Please verify that the package.json has a valid “main” entry (While processing: “F:Programming herop-hero course-(Main-course)milestone-12( doctor portal project)module-69-74(final project)doctor-portal-client-sitenode_modulesbabel-preset-react-appdependencies.js”)

DiscordAPIError: Invalid Form Body message_id: Value “10s” is not snowflake

My code

I have a discord bot using djs with over 216 commands and i was trynna make a giveaway command without using discord-giveways npm

I have tried asking many many people for solutions and everyone has said that they dont know. I looked on google, not a single useful answer. I would appreciate it if someone could help me out on this

I get this error:

 throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Invalid Form Body
message_id: Value "10s" is not snowflake.

This happens when i run the giveaway. it works fine till it ends, once it ends this error occurs before i even try to reroll the giveaway

if i change the args from 1 and 2 to 2 and 3 it will say unknown message

  if(args[1].toLowerCase() === "reroll" && message.member.permissions.has("MANAGE_GUILD") || message.member.roles.cache.find(r=> r.name === "Giveaway Manager")) {
                                let messageID = message.channel.messages.fetch(args[2])
                                if(!messageID) return message.reply({embeds: [new Discord.MessageEmbed()
                                    .setColor(colours.pink)
                                    .setTitle(`${emotes.Error} MISSING ARGUEMENT`)
                                    .setDescription("*Bakaa~* You need to provide a message ID for me to reroll!")
                                    .setTimestamp()
                                ], allowedMentions: {repliedUser: false}
                            })
                            if(messageID) {
                                for (let i = 0; i < winnerCount; i++) {
                                index2 = Math.floor(Math.random() * (participants.length -1));
                                if(!RerolledWinners.includes(participants[index2])) {
                                    RerolledWinners.push(participants[index2]);
                                } else i--;
                            }

Image to show how far it goes till it causes the error

React – Upload Build to Netlify Fail – Black Screen

I am uploading a build for the very first time and I am using Netlify for it.

I’ve linked my account to GitHub and uploaded my project from there. For the build command I entered “npm run build” and for the publish directory “build“. However once the website deployed all I have is a black screen. What can I do to fix it ?

Here is also my package.json:

 {
  "name": "netflix_clone",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.0",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "axios": "^0.25.0",
    "firebase": "^9.6.3",
    "framer-motion": "^4.1.17",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-icons": "^4.3.1",
    "react-router-dom": "^6.0.2",
    "react-scripts": "4.0.3",
    "router-dom": "^2.2.6",
    "sass": "^1.44.0",
    "swiper": "^7.4.1",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Thank you for your help.

How to pause the video when popup is closed in bootstrap?

I am using Bootstrap 5 Modal Popup, I embedded an Iframe in the popup box and everything is working fine but the thing is that When I am closing the Popup the video is not stoping/pausing and even the Popup is closed it is still Running in the background and I tried to stop it via Jquery but don’t know why it is not working.
So can anyone please tell me how to pause/stop the video when the popup is closed?

$(document).ready(function() {
  var url = $("#how-it-works-video").attr('src');

  $("#exampleModal").on('hide', function() {
    $("#how-it-works-video").attr('src', '');
  });

  $("#exampleModal").on('show', function() {
    $("#how-it-works-video").attr('src', url);
  });
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>





<!-- Button trigger modal -->
<a class="btn btn-primary" type="button" data-bs-toggle="modal" data-bs-target="#exampleModal">
  How it works
</a>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">

  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      
      
      <div class="modal-body">      
      <iframe id="how-it-works-video" width="100%" height="100%" src="https://www.youtube.com/embed/MC7reQGDBI0" title="YouTube video player" frameborder="5" allowfullscreen></iframe>
      </div>


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


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Error Can’t resolve ‘react-scroll’ module in react

Module not found: Error: Can’t resolve ‘react-scroll’ in
‘D:ProjectsTemp Projectsmy-appsrccomponents’ assets by path
static/ 31.8 MiB

ERROR in ./src/components/ButtonElements.js 4:0-36 Module not found:
Error: Can’t resolve ‘react-scroll’ in ‘D:ProjectsTemp
Projectsmy-appsrccomponents’ @
./src/components/HeroSection/index.js 8:0-43 52:37-43 @
./src/pages/index.js 7:0-52 40:35-46 @ ./src/App.js 6:0-27 17:19-23
36:35-39 @ ./src/index.js 6:0-24 9:33-36

enter image description here

import styled from "styled-components";
import {Link} from 'react-scroll';


export const Button = styled.button`
    border-radius: 50px;
    background: ${({primary}) => (primary ? '#01BF71' : '#010606') };
    white-space: nowrap;
    padding: ${({big}) => (big ? '14px 48px' : '12px 30px')};
    color: ${({dark}) => (dark ? '#010606' : '#fff')};
    font-size: ${({fontBig}) => (fontBig ? '20px' : '16px')};
    outline: none;
    border: none;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.2s ease-in-out;

    &:hover {
        transition: all 0.2s ease-in-out;
        background: ${({primary}) => (primary ? '#fff' : '#01BF71') };
    }


`;

react-icons/fa

import React from "react";
import { FaFacebook, FaInstagram, FaYoutube, FaTwitter, FaLinkedin } from "react-icons/fa";
import { animateScroll as scroll } from "react-scroll/modules";

import { 
    FooterContainer,
    FooterWrap,
    FooterLinksContainer,
    FooterLinksWrapper,
    FooterLinksItems,
    FooterLinkTitle,
    FooterLink,
    SocialMedia,
    SocialMediaWrap,
    SocialLogo,
    WebsiteRights,
    SocialIcons,
    SocialIconLink,


} from "./FooterElements";

**

App.js

import React from 'react';
import './App.css';
import Home from './pages';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import SigninPage from './pages/signin';
import Navbar from './components/Navbar';




function App() {
  return (
    <Router>
      
      <Routes>
        <Route path= "/" component={Home} exact />
        <Route path= "/signin" component={SigninPage} exact />
      </Routes>
      <Home />
     
    </Router>
  );
}

export default App;

**

MongoDB: Aggerate query is not passing value inside the function

I am facing a problem with the Mongoose aggregation query. I have the following schema which is an array of objects and contains the endDate value.

[
  {
    "id": 1,
    "endDate": "2022-02-28T19:00:00.000Z"
  },
  {
    "id": 2,
    "endDate": "2022-02-24T19:00:00.000Z"
  },
  {
    "id": 3,
    "endDate": "2022-02-25T19:00:00.000Z"
  }
]

So, during the aggregation result, I have to add a new field name isPast, It contains the boolean value, and perform the calculation to check if the endDate is passed or not. If it is already passed, then isPast will be true otherwise false.

I am using isBefore function from the moment library which returns the boolean. But inside this function facing a problem regarding passing the endDate value. $endDate is passing as a string, not a value.

Is there a way to pass the value of endDate inside the function?

const todayDate = moment(new Date()).format("YYYY-MM-DD");

db.collection.aggregate([
  {
    $addFields: {
      "isPast": moment('$endDate', 'YYYY-MM-DD').isBefore(todayDate)
    },
    
  },
  
])