Javascript inside HTML not working in Angular

I have JavaScript for my navbar under my HTML which is to close and open the navbar. However, none of the functions work for javascript. Please help me how I can fix this to make it work.
I have tried script under html and also tried putting my javascript under assets. However, I do not know how to call that file from my navbar.component.ts file.

JavaScript:

`<script>
let arrow = document.querySelectorAll(".arrow");
console.log(arrow);
for (var i = 0; i < arrow.length; i++) {
  arrow[i].addEventListener("click", (e) => {
    let arrowParent = e.target.parentElement.parentElement;
    arrowParent.classList.toggle("showMenu");
  });
}

let sidebar = document.querySelector(".sidebar");
let sidebarBtn = document.querySelector(".bx-menu");
sidebarBtn.addEventListener("click", () => {
  sidebar.classList.toggle("close");
});
</script>

`

I want the images on my page to be clicked as many times as I want

There are 3 images on my index page. I want the images to be clicked as much as the value I get from the input, but it goes into an endless loop in the code I wrote.

inputField.addEventListener("keyup",(e)=>{
        let inputVal=inputField.value;
        

        if(e.key=="Enter" && inputVal.length > 0){
            inputField.value="";
            let i=0;
            while(i<inputVal){
                for (const image of optionImages) {
                    image.addEventListener("click",()=>{
                        i++;
                    })
                }
                console.log(i);
            }
            
        }
    });

Converting decimal to hex and make sure they are numbers

I am trying to create an error catch while entering an odometer reading. It seems that my ODO value isn’t being converted to HEX and will only allow ODO values between 30 and 39 (instead of the HEX values 30 to 39 which are decimal numbers 0-9).

<script language="JavaScript">
function checkFormStartShift()
{
    var vODOstart = document.startshift.odostart.value;
    vConvertHex = vODOstart.toString(16);
    var vError = "no";
    
    for (var i = 0; i < vConvertHex.length; i=i+2) 
    {
        let result = vConvertHex.substr(i, 2);
        if (result < 30 || result > 39)
        {
            alert("Starting KMs should be numbers only");
            vError = "yes";
            return false;
        }
    }
            
    if (vODOstart < 0 && vError == "no")
    {   
        return true;
    }
               
    else if (vODOstart <= 0)
    {
        alert("Starting ODO cannot be 0 or negative.  Please correct.");
        return false;
    }   
    
}
</script>

Discord.js v14 DiscordAPIError[50035]: Invalid Form Body

To make a new bot, I wrote the code and run it. But I saw error happen every time I run my code. I don’t know the cause about this error. And I want to solve this. Please help.

Error:

DiscordAPIError[50035]: Invalid Form Body
0.name[BASE_TYPE_REQUIRED]: This field is required
    at handleErrors (C:Usersgims3OneDrive바탕 화면discord.js [email protected]:640:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.runRequest (C:Usersgims3OneDrive바탕 화면discord.js [email protected]:1021:23)
    at async SequentialHandler.queueRequest (C:Usersgims3OneDrive바탕 화면discord.js [email protected]:862:14)
    at async REST.request (C:Usersgims3OneDrive바탕 화면discord.js [email protected]:1387:22)
    at async client.handleCommands (C:Usersgims3OneDrive바탕 화면discord.js V14srcfunctionshandlershandleCommands.js:27:7) {
  requestBody: { files: undefined, json: [ [Object], [Object] ] },
  rawError: {
    code: 50035,
    errors: { '0': [Object] },
    message: 'Invalid Form Body'
  },
  code: 50035,
  status: 400,
  method: 'PUT',
  url: 'https://discord.com/api/v10/applications/1043561701905272915/commands'
}

My command handler:

const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v10");
const fs = require("fs");

module.exports = (client) => {
  client.handleCommands = async () => {
    const commandFolders = fs.readdirSync(`./src/commands`);
    for (const folder of commandFolders) {
      const commandsFiles = fs
        .readdirSync(`./src/commands/${folder}`)
        .filter((file) => file.endsWith(".js"));

      const { commands, commandArray } = client;
      for (const file of commandsFiles) {
        const command = require(`../../commands/${folder}/${file}`);
        commands.set(command.data.name, command);
        commandArray.push(command, command.data.toJSON());
      }
    }

    const clientId = "1043561701905272915";
    const guildId = "775692469315698739";
    const rest = new REST({ version: "10" }).setToken(process.env.token);
    try {
      console.log("Started refreshing application (/) commands.");

      await rest.put(Routes.applicationCommands(clientId, guildId), {
        body: client.commandArray,
      });

      console.log("Successfully reloaded  application (/) commands.");
    } catch (error) {
      console.error(error);
    }
  };
};

I read discord developer portal but I don’t know how to fix it.

Access to XMLHttpRequest at ‘http://localhost:8800/api/auth/login’ from origin ‘http://127.0.0.1:5173’ has been blocked by CORS policy in React JS

I am trying to make a request from my client side React JS to server side Node JS and Backend on MongoDB. But whenever I am trying to make a post request for my login functionality but it is giving me the below error and
I am using VITE for my react project and my route is : http://127.0.0.1:5173/login

login:1 Access to XMLHttpRequest at 'http://localhost:8800/api/auth/login' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
{
    "message": "Network Error",
    "name": "AxiosError",
    "stack": "AxiosError: Network Errorn    at XMLHttpRequest.handleError (http://127.0.0.1:5173/node_modules/.vite/deps/axios.js?v=b0cda0cd:1440:14)",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "adapter": [
            "xhr",
            "http"
        ],
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {},
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json"
        },
        "withCredentials": true,
        "method": "post",
        "url": "http://localhost:8800/api/auth/login",
        "data": "{"username":"as","password":"as"}"
    },
    "code": "ERR_NETWORK",
    "status": null
}
POST http://localhost:8800/api/auth/login net::ERR_FAILED

Below is my client side code:

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const res = await axios.post(
        "http://localhost:8800/api/auth/login",
        {
          username,
          password,
        },
        {
          withCredentials: true,  
        }
      );
      console.log(res);
    } catch (err) {
      setError(err);
      console.log(error);
      console.log(err);
    }
  };

  return (
    <div className="login">
      <form onSubmit={handleSubmit}>
        <h1>Sign in</h1>
        <label htmlFor="">Username</label>
        <input
          type="text"
          name="username"
          placeholder="ahmed"
          onChange={(e) => setUsername(e.target.value)}
        />

        <label htmlFor="">Password</label>
        <input
          type="password"
          name="password"
          placeholder="password"
          onChange={(e) => setPassword(e.target.value)}
        />

        <button type="submit">Login</button>
      </form>
    </div>
  );
};

This is my server.js file:

const express = require("express");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const dotenv = require("dotenv");
const userRoute = require("./routes/user.route.js");
const gigRoute = require("./routes/gig.route.js");
const orderRoute = require("./routes/order.route.js");
const messageRoute = require("./routes/message.route.js");
const conversationRoute = require("./routes/conversation.route.js");
const reviewRoute = require("./routes/review.route.js");
const authRoute = require("./routes/auth.route");
const cors = require("cors");

const app = express();

app.use(express.json());
app.use(cookieParser());
dotenv.config();
mongoose.set("strictQuery", true);

function handleError(error) {
  console.error("An error occurred:", error);
}

async function startServer() {
  try {
    await mongoose.connect(process.env.MONGO);
    console.log("conneted!");
  } catch (error) {
    handleError(error);
  }
}

app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
// app.use("/api/gigs", gigRoute);
// app.use("/api/orders", orderRoute);
// app.use("/api/conversations", conversationRoute);
// app.use("/api/messages", messageRoute);
// app.use("/api/reviews", reviewRoute);

// error handling middleware
app.use((err, req, res, next) => {
  const errorStatus = err.status || 500;
  const errorMessage = err.message || "Something went wrong!";

  return res.status(errorStatus).send(errorMessage);
});

//
app.use( //here i am using cors
  cors({
    origin: "*",
  })
);

app.listen(8800, () => {
  startServer();
  console.log("app is listening at 8800!");
});

auth.route.js file:

const express = require("express");
const { register, login, logout } = require("../controllers/auth.controller");

const router = express.Router();

router.post("/register", register);
router.post("/login", login);
router.post("/logout", logout);

module.exports = router;

and in the end it is my auth.controller.js file:

const User = require("../models/user.model");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { createError } = require("../utils/createError");
const login = async (req, res, next) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    if (!user) return next(createError(404, "user not found!"));

    const isCorrect = bcrypt.compareSync(req.body.password, user.password);
    if (!isCorrect)
      return next(createError(400, "Wrong password or username!"));

    const token = jwt.sign(
      {
        id: user._id, //object id
        isSeller: user.isSeller,
      },
      process.env.JWT_KEY
    );

    const { password, ...info } = user._doc;
    res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5173");
    res
      .cookie("accessToken", token, {
        httpOnly: true,
      })
      .status(200)
      .send(info);

    res.status(200).send(user);
  } catch (err) {
    next(err);
  }
};
const logout = async (req, res) => {
  res
    .clearCookie("accessToken", {
      sameSite: "none",
      secure: true,
    })
    .status(200)
    .send("User has been logged out!");
};
const register = async (req, res, next) => {
  try {
    const hash = bcrypt.hashSync(req.body.password, 5);
    const newUser = new User({ ...req.body, password: hash });
    await newUser.save();
    res.status(201).send("User has been created");
  } catch (err) {
    next(err);
  }
};
module.exports = {
  login,
  logout,
  register,
};

I don’t know why I can’t pop up the container with correct info. check the code please, thank you in advance

I have an index.php file that contains a table. here is screenshot enter image description here

I want when I click on the name here how is the name cell in my code is

 <td style="display:none;">$id</td>
<td ><a ondblclick="displyPopUp('playerInfo_popup', this);"><span></span> $name </a></td>

it shows a popup box with more info about the name being clicked where I need to get the id of the person in order to retrieve more about him from the database.
The pop up code is :

echo <<<HTM
<div class="popup-container" id="playerInfo_popup">
    
    <div class="popup-content ">
HTM;

$person_id =  $_GET['id'];

echo <<<HTM
    person id is : $person_id 
       
            
        </div>
    </div>
</div>
HTM;

and the js code is

async function displyPopUp(popId, element){
  let id = element.parentElement.parentElement.children[0].textContent;
  const params = new URLSearchParams(window.location.search);
  const current_href = window.location.href;
  const state = {id:12}
  const title = 'test'
  const url = current_href + '?id=' + id + '&playerInfo_popup=1';

  await new Promise(resolve => {
    history.pushState(state, title, url);
    resolve();


  });
  
  foo(popId, current_href);
}




function foo(popId, current_href) {
  const popupContainer = document.getElementById('playerInfo_popup');
    const closeButton = document.querySelector('.fa-circle-xmark')
      popupContainer.classList.add('show');
      closeButton.addEventListener('click', () => {
        popupContainer.classList.remove('show');
        window.location.href = current_href;
      });
      popupContainer.addEventListener('dblclick', () => {
        popupContainer.classList.remove('show');
      });
}

the popup is being displayed and the popup is showing but the id is not shown here is screen shot after I click any name enter image description here

the url is being updated but $_GET[‘id’] is still null
please help me to fix this code

Why are the tiles not appearing when they should be drawn?

I am making a game, I have the basic player movement down and its sprite animation. However the grass tiles I’m trying to paste onto the background, do not appear to be drawn.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// Variables
var tileSize = 32;
var tilex = Math.ceil(canvas.width / tileSize);
var tiley = Math.ceil(canvas.height / tileSize);
var tiles = [];
var player = [];
var playerState = 'idle';
var keyPresses = {};
var userSize = 128;

// Event Listeners
window.addEventListener('keydown', keyDownListener, false);
function keyDownListener(event) {
  keyPresses[event.key] = true;
};

window.addEventListener('keyup', keyUpListener, false);
function keyUpListener(event) {
  keyPresses[event.key] = false;
  playerState = 'idle';
};

//TileImages grass, stone, and structure
for (let i = 0; i < 156; i++) {
    tiles[i] = new Image();
    tiles[i].src = 'performanceTask Assets/tiles/tile' + i.toString() + '.png';
};

//Player Images idle and movement
for (let i = 0; i < 40; i++) {
    player[i] = new Image();
    player[i].src = 'performanceTask Assets/player/player' + i.toString() + '.png';
};

class Map {
    xTileLocation = 0;
    yTileLocation = 0;
    grassLand() {
        for (let i = 0; i < this.tiley; i++) {
            for (let j = 0; j< this.tilex; j++) {
                ctx.drawImage(this.tiles[0], this.xTileLocation, this.yTileLocation);
                this.xTileLocation += this.tileSize;
            };
            this.xTileLocation = 0;
            this.yTileLocation += this.tileSize;
        };
        this.xTileLocation = 0;
        this.yTileLocation = 0;
    };
};

class Player {
    x = canvas.width/2;
    y = canvas.height/2;

    tick = 0;
    playerImage = player;
    state = playerState;

    movementSpeed = 5;
    draw() {
        this.state = playerState

        // Movement
        if (keyPresses.w) {
            this.y -= this.movementSpeed;
            playerState = 'moving';
        }
        if (keyPresses.s) {
            this.y += this.movementSpeed;
            playerState = 'moving';
        }
        if (keyPresses.a) {
            this.x -= this.movementSpeed;
            playerState = 'moving';
        }
        if (keyPresses.d) {
            this.x += this.movementSpeed;
            playerState = 'moving';
        }





        // IDLE STATE
        if (this.state == 'idle') {
            if(this.tick==20 || this.tick > 20) {
                this.tick = 0;
            };
            ctx.drawImage(this.playerImage[this.tick], this.x - 64, this.y + 64, 128, 128);
        }
        else {
            if (this.state == 'moving') {
                if(this.tick < 21 || this.tick == 39) {
                    this.tick = 21;
                };
                ctx.drawImage(this.playerImage[this.tick], this.x -64, this.y + 64, 128, 128);
            }
        }
        this.tick = this.tick + 1;
    };
};

let user = new Player();
let map = new Map();
function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    map.grassLand();
    user.draw();
};
setInterval(gameLoop, 1000/24);

The code that is not working is located in the Map class.

I have tried to read through the javascript documentation, but have found nothing. There are no errors and nothing seems to work. Each tile is 32px by 32px.

adding texture and wireframes in three-globe

I’m using three-globe to try to show movements on the globe. The regular line are tough to visualize if they overlap (due to lack of border), so was looking to draw as cylinders. Thus far I’ve had no luck (see pic) and wonder if I’m calling the object correctly.

enter image description here

 const cylinderData = [...Array(N_cylinders).keys()].map(() => ({
  lat: (Math.random() - 0.5) * 180,
  lng: (Math.random() - 0.5) * 360,
  lat2: (Math.random() - 0.5) * 180,
  lng2: (Math.random() - 0.5) * 360,
  alt: path_altitude ,
  radius: Math.random() * 5,
  color: 'red'
  }));






.customLayerData(cylinderData )
.customThreeObject(d => {
  let pointX = Globe.getCoords(d.lat, d.lng, d.alt);
  let pointY = Globe.getCoords(d.lat2, d.lng2, d.alt);
  let direction = new THREE.Vector3().subVectors(pointY, pointX);
 const  cylinder_material = new THREE.MeshBasicMaterial( {color: 0xffff00} );
  let edge_size =4;
 geometry = new THREE.CylinderGeometry(edge_size , edge_size , direction.length(), 16, 14, true);
 
geometry.applyMatrix4(new THREE.Matrix4().makeTranslation(0, direction.length() / 2, 0));

geometry.applyMatrix4(new THREE.Matrix4().makeRotationX(THREE.MathUtils.degToRad(90)));
    
let Edge_array = new THREE.Mesh(geometry,  cylinder_material );
Edge_array.position.copy (pointX);
Edge_array.lookAt(pointY); 
scene.add(Edge_array) ;

MERN stack regex filter with search box and checkbox

I am trying to learn how MERN stack is working together by learning by doing and I am following these tutorials from bezcoder: Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code)

Example data from server

[
  {
    "id": "5f9bdace778082303c859248",
    "title": "How to cook noodles",
    "description": "This is a tutorial about how to cook noodles in under 10 minutes.",
    "published": false
  },
  {
    "id": "5f9bdae3778082303c859249",
    "title": "How to bake a chocolate cake",
    "description": "This is a tutorial about how to bake chocolate cake using cocoa powder.",
    "published": true
  }
]

Current situation
Currently, the front-end of the App has a search bar, where I can search and filter the data by the “title” of the tutorial (e. g. “noodles” in order to get the first one).
I found out that this is done by the following snippets:

  1. tutorial.controller.js
exports.findAll = (req, res) => {
  const title = req.query.title;
  var condition = title ? { title: { $regex: new RegExp(title), $options: "i" } } : {};

  Tutorial.find(condition)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};
  1. services/tutorial.service.js (in Reactjs)
import http from "../http-common";

class TutorialDataService {

...
  
  findByTitle(title) {
    return http.get(`/tutorials?title=${title}`);
  }
}

export default new TutorialDataService();

What I would like to know is, how can I change those codes so that I can filter by words from “title” and “description” from the search box, as well as published:true by a checkbox.

If the front end would look like this:
front end search and checkbox

My attempts

  1. tutorial.controller.js
exports.findAll = (req, res) => {
  const title = req.query.title || "";
  const description = req.query.description || "";
  const published = req.query.published;

  Tutorial.find(
    {
    $or: [
        {title: { $regex: new RegExp(title), $options: "i"},
         description: { $regex: new RegExp(description), $options: "i"},}
    ]
    $and: [
        .... and here if checked, then only show published, else show all ....
    ]

}

  )
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving tutorials."
      });
    });
};
  1. services/tutorial.service.js (in Reactjs)
import http from "../http-common";

class TutorialDataService {

...
  
  findByTitle(title, description, published) {
    return http.get(`/tutorials?title=${title}`, `/tutorials?description=${description}`, `/tutorials?published=${published}`);
  }
}

export default new TutorialDataService();

I’m not sure if that’s even the correct usage of findByTitle and how I have to implement OR and AND function correctly.

Unable to Display Image from HTML Form

So I have this code in an HTML form over here that I’m using to upload data to MYSQL Workbench. I use it to upload to a specific page on my NextJS program. This is the HTML code that I use, “newgame.html”.

<!DOCTYPE html>
<html lang = "en">
<head>
<style>
body {background-color: silver;}
h1   {color: blue;}
p    {color: blue;}
input {
  width: 30%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}
</style>
<title>
New Game Addition
</title>
</head>
<body>
    <p style= "font-size:40px">Add a New Game</p>
<form method="post" action="/api/newgame" enctype="multipart/form-data">
    <input type="number" id = "ProductID" name="ProductID" placeholder="Product ID"> <br />
    <input type="text" id = "ProductName" name="ProductName" placeholder="Name of Product."> <br />
    <input type="text" id = "ProductDescription" name="ProductDescription" placeholder="Describe the Product."> <br />
    <input type="file" id = "ProductImage" name="ProductImage" placeholder="Put in Image"> <br />
    <input type="number" step="0.01" id = "ProductPrice" name="ProductPrice" placeholder="0.00"> <br />
    <input type="date" id = "DateWhenAdded" name="DateWhenAdded" placeholder="01/01/2001"> <br />
    <input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>

And this is the API that I use to actually get everything uploaded into the database itself. This one is “newgame.js”.

import mysql from "mysql2/promise";
import multiparty from "multiparty";

export default async function handler(req, res) {
  const dbconnection = await mysql.createConnection({
      host: "localhost",
      database: "onlinestore",
      port: 3306,
      user: "root",
      password: "Jennister123!",
  });
  try {
    const form = new multiparty.Form()

    const data = await new Promise((resolve, reject) => {
      form.parse(req, function (err, fields, files) {
        if (err) reject({ err })
        resolve({ fields, files })
      })
    })
    const query = "INSERT INTO games (ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded) VALUES(?,?,?,?,?,?)";
    const values =
    [parseInt(data.fields.ProductID), 
     data.fields.ProductName[0], 
     data.fields.ProductDescription[0], 
     data.files.ProductImage,
     parseFloat(data.fields.ProductPrice), 
     data.fields.DateWhenAdded[0]]

    await dbconnection.execute(query, values);
    dbconnection.end();

    res.status(200).json({ games: data });
    

} catch (error) {
    res.status(500).json({ error: error.message });
}
}
export const config = {
  api: {
    bodyParser: false,
  }
}

I do have all the data here I have the information in the form, which includes the image file that I want to upload.
enter image description here

However, upon uploading it, I end up getting this, and not the image as a whole. I feel like the image is not uploading properly to MYSQL Workbench somehow.

enter image description here

I’d like to know how I can alleviate this problem to make the image display in here as well as the MYSQL Database I set up in MYSQL Workbench. Any suggestions?

When I have done debugging, I notice this in the values editor in MySQL Workbench in the table. It wasn’t image data at all. It was just text.

[{"fieldName":"ProductImage","originalFilename":"ChutesandLadders.jpg","path":"C:\Users\misty\AppData\Local\Temp\4WxaIL4vePu073B3NJ8ZuQqu.jpg","headers":{"content-disposition":"form-data; name="ProductImage"; filename="ChutesandLadders.jpg"","content-type":"image/jpeg"},"size":160628}]

Fetch-retry npm testing

retry npm package with global fetch.

https://www.npmjs.com/package/fetch-retry

Using it via:

const fetch = require('fetch-retry')(global.fetch)

For my unit tests, the suite fails saying fetch must be a function. However if I remove fetch-retry package my tests work. Fetch-retry is wrapping global fetch. Anyway to mock/test this?

My unit tests is something like this, as you see it doesn’t have fetch-retry

import React from 'react';
import { render, screen } from '@testing-library/react';

import Test from "./Test";



describe("Test", () => {
    let originalFetch;

    beforeEach(() => {
        originalFetch = global.fetch;
    global.fetch = jest.fn(() => Promise.resolve({
        json: () => Promise.resolve({
            value: "Testing something!"
        })
    }));
});

afterEach(() => {
    global.fetch = originalFetch;
});

it('Should have proper description after data fetch', async () => {

    // need to put mock logic here to make it work

    render(<Test />);
    const description = await screen.findByTestId('description');
    expect(description.textContent).toBe("Testing something!");
   });
});

get data from database using ajax and into javascript array

I’m not getting any data from the database to javascript but I get data to PHP

I use Ajax to get data from the database and get data from the PHP file to javascript and I want to filter the data using javascript so I fetch data using javascript to display the products I’m not getting data to javascript but get data to PHP file.

$.ajax({
    url: 'user.php',
    type: 'GET',
    datatype: 'json',
    success: function (data) {
    }
});


function ajax() {
    const xhr = new XMLHttpRequest;
    xhr.open('GET', 'user.php', true);
    xhr.send();
    xhr.onload = () => {
        if (this.readyState == 4 && this.status == 200) {
            let products = JSON.parse(this.responseText);
            console.log(products);
        }
    }
}

const section = document.querySelector('.cards');
const btnContainer = document.querySelector('.top ul');


window.addEventListener('DOMContentLoaded', () => {
    displayProductItems(products);
    displayMenuButtons();

});
function displayProductItems(productItems) {
    let displayProducts = productItems.map((item) => {
        return `<div class="card">
            <img src="${item.image}" alt="">
            <h3>${item.title}</h3>
            <div class="bottom">
              <span class="text-accent-2">${item.category}</span>
              <span class="price">$${item.price}</span>
            </div>
          </div>`;
    });
    displayProducts = displayProducts.join("");
    section.innerHTML = displayProducts;
}

function displayMenuButtons() {
    const sub_categories = products.reduce((values, item) => {
        if (!values.includes(item.sub_category)) {
            values.push(item.sub_category);
        }
        return values;
    }, ['all']);

    const buttons = sub_categories.map((sub_cat) => {
        return `<li><button class="filter-btn" data-id="${sub_cat}">${sub_cat}</button></li>`
    }).join("");

    btnContainer.innerHTML = buttons;
    const filterBtn = document.querySelectorAll('.filter-btn');
    filterBtn.forEach((btn) => {
        btn.addEventListener('click', (e) => {
            const sub_cat = e.currentTarget.dataset.id;
            const productsSubCat = products.filter((productItem) => {
                if (productItem.sub_category === sub_cat) {
                    return productItem;
                };
            });
            if (sub_cat === 'all') {
                displayProductItems(products);
            } else {
                displayProductItems(productsSubCat);
            }
        });
    });
}

Jquery Scrolling Smooth

I am using this code which works but the scrolling is too abrupt and fast. I would like to make it much smoother and slower.

 document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

React Promise Based Modal

I have developed the code for the modal in React. I wanted to make a generic modal for the application and I came up with a solution but god knows how. Can anyone take a look at the code and explain why is it working and how can we make it better?

I’m writting the code snippet in Stackoverflow for the first time and I’m getting error in the react code. Could anyone please see what is the issue.

const {useState} = React;

//this variable is getting assigned the resolve function of a Promise.
// If the variable is defined inside the App() component then it does not work and throws undefined
// can anyone explain how this is working.
let resolveHelper;
const App = ()=> {
  const [data, setData] = useState(["Apple", "Banana", "berries", "Kiwi"]);
  const [isModalHidden, setIsModalHidden] = useState(false);

  const handleDelete = async (fru) => {
    try {
      const res = await handlePromise();
      if (res) {
        // Delete Logic will come here
        console.log("We will delete you");
      } else {
        // No is clicked escape logic will come here
        console.log("you can go");
      }
    } catch (err) {
      console.log(err);
    }
  };

  // This function is returning a promise and assigning resolve function to a variable
  const handlePromise = () => {
    setIsModalHidden((prev) => !prev);
    return new Promise((resolve) => {
      resolveHelper = resolve;
    });
  };

  // This function is listening to the button click of Modal
  const handleConfirmation = (confirmation) => {
    return new Promise((resolve, reject) => {
      if (confirmation) resolveHelper(true);
      else resolveHelper(false);
    });
  };

  // Mapping the data to HTML
  const dataContent = data.map((fruit) => (
    <li key={fruit}>
      {fruit} <button onClick={() => handleDelete(fruit)}>delete</button>
    </li>
  ));

  // Modal show or hide based on the flag value
  const displayValue = isModalHidden ? "block" : "none";
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <ul>{dataContent}</ul>

      <div style={{display:`${displayValue}`}}>
        Are you sure you want to delete this
        <button onClick={() => handleConfirmation(true)}> Yes</button>
        <button onClick={() => handleConfirmation(false)}> No </button>
      </div>
    </div>
  );
}

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App/>
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>