Saving files in async loop promise

For example, I have a function : async updateOne(track) that get audio file of each track and save it on a repertory after making some changes to the audio.

This is the code that got all the tracks and loop on it and use the updateOne function on each track :

exports.updateAllTracksWithNewTag = async (req, res) => {
    try {
        const allTracks = await Tracks.findAll()

        await Promise.all(
            allTracks.map(async (track) => {
                await this.updateOne(track)
            })
        )

        return res.status(200).json({ message: 'All tracks changes done' })
    } catch (error) {
        return ResponseErrorFormated.responseError(error, res)
    }
}

updateOne(track) function :

exports.updateOne= async (track) => {
    const filesToDeleteFromTemp = []

    try {
        const fileAudioURL = track.MP3_audio_url
        const originalFileReadstream = await AWSS3Utils.getReadStream(
            URLConfig.URL_ASSETS.PRIVATE.USERS_TRACKS_AUDIOS.path.slice(1) + fileAudioURL
        )
        const tempPathToSaveStreamGetted = 'assets/temp/audios/'
        
        // Saving the file to the temp repertory
        await FilesUtils.saveReadStreamAsFile(originalFileReadstream, tempPathToSaveStreamGetted, fileAudioURL)

        filesToDeleteFromTemp.push(tempPathToSaveStreamGetted + fileAudioURL)

        const fileInfosForTag = {
            path: tempPathToSaveStreamGetted + fileAudioURL,
            filename: fileAudioURL,
        }
        
        // Make process to the audio track that take 5sec minimum
        const resultTaggedMP3 = await FilesFormater.createTaggedAudioFromMP3(fileInfosForTag)
        const readStreamTaggedMP3 = resultTaggedMP3.readStream
        const finalFilePathTaggedMP3 = resultTaggedMP3.finalFilePath
        const finalFileNameTaggedMP3 = resultTaggedMP3.finalFileNameTaggedMP3
        const newFileKeyMP3 =
            URLConfig.URL_ASSETS.PUBLIC.USERS_TRACKS_TAGGED.path.slice(1) + finalFileNameTaggedMP3

        filesToDeleteFromTemp.push(finalFilePathTaggedMP3)
        
        // ReUpload the new file changed
        await AWSS3Utils.uploadFileFromReadstream(readStreamTaggedMP3, newFileKeyMP3)
        
        // Delete files from temp repertory
        await FilesUtils.unlinkFiles(filesToDeleteFromTemp)
    } catch (error) {
        await FilesUtils.unlinkFiles(filesToDeleteFromTemp)

        throw error
    }
}

It should save the file of the first track, then wait 5sec or more for process, then reupload the file and delete it, and after do the same with the next track.
But when I execute it, he save all the files to the repertory and just after he make the process of each track and reupload it and delete it.

How can I prevent it to save all the track files in one time ? Because it take a lot of powerful when he do this quickly.

How to render SVG component using props?

I’m trying to render an SVG using props of a function. Any help on how to achieve this?

Here is the code:

import React from "react";
import Camera from "../icons/Camera.svg";

export default function Button(props) {
  console.log(props.icon);
  return (
    <button
      type="button"
      className="mx-auto mb-2.5 flex items-center gap-2 rounded-lg border border-gray-300 px-3.5 py-2 text-sm font-medium text-gray-700 drop-shadow-sm"
    >
      {props.icon} /* SVG ICONS GOES HERE*/
      {props.label}
    </button>
  );
}

Poll interval option on Apollo client useQuery hook not working

I have a simple forum-like app using apollo server and client(react) and I am trying to periodically update the posts on the main page using the pollInterval option on the useQuery hook. It doesn’t seem to actually do anything, when I make a new post the page isn’t updated.

Here is my query to get all the posts in the DB,

  const { loading, data } = useQuery(QUERY_POSTS, {
    pollInterval: 1000,
  });

and I am mapping through the data here

{loading && <div>loading....</div>}

        {data?.posts.map((post) => (
          <Card className="mb-5 w-50 " key={post._id}>
            {post.imgUrl && <Card.Img variant="top" src={post.imgUrl} />}

            <Card.Body>
              <Card.Text>{post.postText}</Card.Text>
              <Button
                variant="warning"
                type="button"
                onClick={(e) => handlePostLike(post._id, e)}
              >
                {post.likeCount} <BsFillEmojiSunglassesFill />
              </Button>
            </Card.Body>
          </Card>
        ))}

Not sure if I should be using a subscription or if I am just using the polling feature incorrectly.

Twilio – can’t process phone number after clicking submit

I’m following this link for the tutorial (via twilio.) and have followed all the
required steps but when I run the localhost and input a number, I get no text message, nor does the window for verification open. It just stays at the same page of “enter your phone number”.

Screenshot of page

Here’s my HTML code
`

<title>Verify SMS Demo</title>
<style>
    #verify-form,
    #response-text {
        display: none;
    }
 </style>
 </head>

<body>
<form id="phone-form">
    <h2>Enter your phone number with country code:</h2>
    <input type="tel" id="phone-number-input" placeholder="15551235555" />
    <input id="phone-submit" type="submit" />
</form>

<form id="verify-form">
    <h2>Enter your verification code:</h2>
    <input type="number" id="otp-input" placeholder="e.g. 123456" />
    <input id="verify-submit" type="submit" />
</form>

<div id="response-text"></div>
 </body>

 <script type="text/javascript" src = "script.js"></script>
</html>`

And here’s my code for script.js

const phoneForm = document.getElementById('phone-form');
const verifyForm = document.getElementById('verify-form');
const responseText = document.getElementById('response-text');

let phoneNumber;

phoneForm.addEventListener('submit', async e => {
e.preventDefault();

phoneNumber = document.getElementById('phone-number-input').value;

const response = await fetch('/send-notification', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({phoneNumber : phoneNumber })
}).catch(e => console.log(e));

if (response.ok) {
phoneForm.style.display = 'none';
verifyForm.style.display = 'block';
}
});

verifyForm.addEventListener('submit', async e => {
e.preventDefault();

const otp = document.getElementById('otp-input').value;

const data = {
phoneNumber: phoneNumber, 
otp: top
};

const response = await fetch('/verify-otp', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify(data)
}).catch(e => console.log(e));

const check = await response.json();

const text = response.ok ? check.status : response.statusText;
responseText.innerHTML = text;

verifyForm.style.display = 'none';
responseText.style.display = 'block';  
});

Is it advisable to use the Express app.use() method call within an async callback?

My question begs a recommendation on best practice.

I wrote a simple Express server that creates a JWT and sends it to the client whenever it (the client) hits an API route.

I have kept the route handler in a separate module and exported it from there because I want to keep the code as modular as possible. I placed the app.use() call that utilizes the middleware for that route within the callback of signJWT() and though this works, I need to know if this is good practice. I did this because the response to be sent back needs the JWT to be signed and ready and this itself is an asynchronous operation. If this isn’t good way to go about it, that is placing an app.use() call within an async callback, I would like to know a better way to do so without having to declare my route handler in the same file as my server entry file (app.js) code.

There are 2 main files to examine here; app.js and routes.js. I have included code from a third file – my client-side JavaScript file (script.js) just for context.

1. app.js (Server + Application-wide middleware usage):

const express = require("express");
const app = express();
const path = require("path");

// JWT Library
const jose = require("jose");

// library for generating symmetric key for jwt
const { createSecretKey } = require("crypto");

// Route handler
const routes = require("./routes");

// Create key 
const secretKey = createSecretKey("MySecret", "utf-8"); 

// Sign the token
async function signJWT() {
  const jwt = await new jose.SignJWT({
    "urn:example:claim": true,
  })
    .setProtectedHeader({ alg: "HS256" })
    .setExpirationTime("1h")
    .sign(secretKey);

  return jwt;
} 

// Expose static content
app.use(express.static(path.join(__dirname, "public"))); 

// This works but is this okay?
signJWT().then((jwt) => app.use("/login", routes({ jwt: jwt })));

app.listen(81); 
console.log("Listening on port 81"); 

The callback in question:

Should app.use() even be in callbacks?

// This works but is this okay?
signJWT().then((jwt) => app.use("/login", routes({ jwt: jwt }))); 

I initially tried to do this, but values from the Async operation in signJWT() weren’t ready and understandably so:

app.use("/login", routes({ jwt: signJWT() }));  

Of course, this works – I used it initially, but I don’t want to clutter app.js with route handler declarations:

app.get("/login", async function (req, res) {
  const jwt = await signJWT();
  res.json({ jwt: jwt });
});

2. routes.js (Route Handler file):

const express = require("express"); 
const router = express.Router();

const wrapper = function (route_params) {

  router.get("/", function (req, res) {
    res.json(route_params);
  });

  return router;
};

module.exports = wrapper; 

3. script.js (Client JavaScript):

document.getElementById("btn").onclick = function () {
  makeRequest("/login");
}; 

function makeRequest(url) {
  fetch(url, {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  })
    .then((res) => res.json())
    .then((json) => console.log(json));
} 

Sample output (in Client’s browser console):

{jwt: 'eyJhbGciOiJIUzI1NiJ9.eyJ1cm46ZXhhbXBsZTpjbGFpbSI6d…Dk3fQ.0C_n25RPQNAP-wxy9PHmpo4SRtXBiiHn0fxGPspqxQM'}

Even though this works, placing an app.use() call within an async callback feels hacky to me and it looks like something that could cause problems later on, to me at least, because Express’ execution of top-level code is contingent on an async callback.

Is there a better way to declare this call and pass the async value from signJWT() to it so that it will be available in the route handler?

Thank you.

how to insert “-” randomly within an array

I have a solution var and a i want to randomly input “-” instead of numbers so the var shows only 25%, 50% , 75% of the numbers

let exampleBoard = [  /// Example for what i want as an output after randomizing
"--74916-5",
"2---6-3-9",
"-----7-1-",
"-586----4",
"--3----9-",
"--62--187",
"9-4-7---2",
"67-83----",
"81--45---"
]

let solution = [
"387491625",
"241568379",
"569327418",
"758619234",
"123784596",
"496253187",
"934176852",
"675832941",
"812945763"
]

how can i do it?

Get input from a form in HTML in Javascript

I am going to get input from a message form (HTML) in js, but it shows The method is not allowed for the requested URL. Can anyone help me find where is the issue? Thanks!

js code:

var socket = io.connect("http://" + document.domain + ":" + location.port);
socket.on("connect", async function () {
  var usr_name = await load_name();
  if (usr_name != "") {
    socket.emit("event", {
      message: usr_name + " just connected to the server!",
      connect: true,
    });
  }
  var form = $("form#msgForm").on("submit", async function (e) {
    e.preventDefault();

    // get input from message box
    let msg_input = document.getElementById("msg");
    let user_input = msg_input.value;
    let user_name = await load_name();

    // clear msg box value
    msg_input.value = "";

    // send message to other users
    socket.emit("event", {
      message: user_input,
      name: user_name,
    });
  });
});

HTML form:

<form id="msgForm" action="" method="POST" style="bottom:0; margin: 0% 0% 0% 0%;">
    <div class="input-group mb-3">
          <input type="text" class="form-control" placeholder="Message" aria-label="Message" id="msg">
          <div class="input-group-append">
            <button class="btn btn-success" type="submit" id="sendBtn">Send</button>
          </div>
    </div>
</form>

Custom React App – Fetch API error when deploying to Heroku

I’ve built a small app in React (not using CRA).

I’ve deployed to Heroku and it’s uploaded fine, but I’m having one issue in which a static JSON file I created myself isn’t fetching (Works fine locally).

I’m getting the below error:

enter image description here

Here is my folder structure:

enter image description here

I’ve tried creating a public folder outside of src but that didn’t help either.

I have a basic Express setup:

enter image description here

Thanks

React Native & Firebase RTDB – having trouble with returns

I’m using React Native with the Firebase SDK (version 9). I have a function that is supposed to check in the database to see if I have an access token stored and when it expires if so. I need the code to return true or false as a result. I think I’m getting tripped up because ‘get’ is asynchronous. Here’s what I have currently:

export const checkToken = (useruid) => {
    const db = getDatabase();
    let outcome = "not set"
    const userRef = ref(db,'/users/'+useruid);
    get(userRef).then((snapshot) => {
      console.log('snapshot is', snapshot)
      let expire_time = snapshot.val().expire_time
      if (expire_time > Date.now() + 180000) {
        console.log('expire time is more than 3 min in the future')
        outcome = true 
        return true
      } else {
        console.log('token is stale, snapshot is ',snapshot)
        outcome = false 
        return false
      } 
    
    }   )
    console.log('outcome is now', outcome)
}

The last console.log appears first (outcome is now not set), and if I call checkToken in another function (as console.log(checkToken(someUserID)), I get back that it is returning undefined. And then I get all the console logging with the successful snapshot retrieval.

I’ve read about promises, and async/await, but I’m having trouble translating that to the Firebase RTBD SDK functions.

Many thanks in advance for help/pointers!

Webpack 5 – asn.define is not a function

The following error prompts in the browser’s console when running my application:

certificate.js:7 
        
       Uncaught (in promise) TypeError: asn.define is not a function
    at eval (certificate.js:7:16)
    at Object.../node_modules/parse-asn1/certificate.js (vendors-node_modules_jsonwebtoken_index_js.js:1142:1)

I’m using "webpack-cli: 4.10.0" "webpack": "^5.73.0".

I tried a bunch of different webpack configs with no success. Here’s how my webpack config file looks right now:

const path = require("path");

module.exports = {
  target: "web",
  context: path.resolve(__dirname, "src"),
  entry: "./index.ts",

  resolve: {
    preferRelative: true,
    extensions: [".tsx", ".ts", ".jsx", ".mjs", ".js", ".json"],
    modules:  ["src", "node_modules",],
    fallback: {
      "crypto": require.resolve("crypto-browserify"),
      "stream": require.resolve("stream-browserify"),
      "vm": require.resolve("vm-browserify"),
      "buffer": require.resolve("buffer")
    }
  },
  
  module: {
    rules: [
      {
        test: /.(ts|tsx|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            "presets": ["@babel/preset-typescript", "@babel/preset-react", "@babel/preset-env"]
          }
        },
      },
      {
        test: /.m?js$/,
        resolve: {
          fullySpecified: false,
        },
      }
    ],
  },
}

React URL changes but component does not render

If I go to “/” or “/details” with Reloading the page manually in browser everything renders fine.

If I go to “/” or “/details” with navbar links the URL changes but the content does not renders.

I tried using “exact” keyword at “/details” route , but it is the same .

React-router-dom: Version: 5.1

App.js:

import { BrowserRouter , Redirect, Route , Switch } from 'react-router-dom';
import './App.css';
import Navbar from './Navbar.js'
import Home from './pages/Home'
import Details from './pages/Details';


function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Navbar />
        <Switch>
          <Route exact path="/" >
            <Home />
          </Route>
          <Route path="/details" >
            <Details />
          </Route>
          <Route path="*">
            <Redirect to="/" />
          </Route>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

Navbar:

import './Navbar.css'
import { NavLink , Link } from 'react-router-dom'
export default function Navbar() {


  return (

        <header >
            <ul >
                <li><Link to="/">Home</Link></li>
                <li><Link to="/details">Details</Link></li>
                <li><a href="https://www.google.com">Google</a></li>
            </ul>
        </header>

  )
}

Is there a way to add new working gear slots in the Minecraft mod Mine and Slash (1.16.5 beta version)?

I am trying to make a modpack centered around this mod, but it needs to have bracelet, belt and charm slots capable of applying statistics to your character. I made a datapack using the way the mod has Rings and Necklaces implemented, and they spawn in correctly with stats on the item types and the gear slots’ souls (though the ingame name for them does not get swapped out for the local names listed in my json’s)…

but equipping them does not actually apply them to your character. I tried reaching out to the developer of the mod for help before this, but that seems to be a dead end.

I have been reading the .class files of the mod to try and grasp what part I’m missing, but it is hard to follow for someone as entry level as I am.

so far i have 1 json for each (belt, bracelet, charm) in my datapack for datammorpgbase_gear_types which are their respective versions of this:

{
  "attacksPerSecond": 1.0,
  "guid": "belt",
  "locname": "Belt",
  "level_range": {
    "start": 0.0,
    "end": 1.0
  },
  "gear_slot": "belt",
  "weight": 1000,
  "weapon_offhand_stat_util": 0,
  "style": "melee",
  "implicit_stats": [],
  "base_stats": [
    {
      "min": 2.0,
      "max": 3.8,
      "stat": "physical_weapon_damage",
      "type": "FLAT"
    },
    {
      "min": 2.0,
      "max": 5.0,
      "stat": "armor",
      "type": "FLAT"
    }
  ],
  "weapon_type": "none",
  "tags": {
    "tags": [
      "belt",
      "jewelry_family"
    ]
  }
}

and 1 for each gear type in datammorpggear_slot that look like this:

{
  "id": "belt",
  "locname": "Belt",
  "weight": 750,
  "energy_cost": 0,
  "model_num": 12,
  "fam": "Jewelry"
}

They each have different “base_stats” than the other 2 types is the main difference between their jsons.

Paperjs how to prevent multiple buttons canceling a drag event on mouseup / allow paperjs only use left button

If you:

  • mousedown left button ↓
  • mousedown right button ↓
  • mouseup right button ↑

The drag event gets canceled by mouseup right button , I don’t want that to happen.
(only want that to happen on mouseup left button , because the event was started by mlb.)

  • I’ve tried preventDefault(), stopPropagation() on both paper and
    window event.
  • I’ve tried emitting mousedown/mousedrag on mouseup tool.emit("mousedown", tool.onMouseDown); not sure if I’m doing something wrong with it, but it runs the mousedown function once and stops, and I don’t think it keeps event data from the first mousedown.

Is there any way to prevent this, maybe even preventing Paperjs from accessing the right button entirely if needed?

I know this has been kind and issue for a while now: https://github.com/paperjs/paper.js/issues/1355
yet there is a fix for accessing 1,2,3.. buttons (event as any).event.button,
there is no fix for preventing the dragging to be set to false.

P.S Appreciate for any help!

How would I write a function that will randomly change up to 2 tiles from each row of my matrix, with a total of no more than 5 tiles per matrix?

I’m building a web-based binary sudoku game that allows the player to change each ’tile’ in the given matrix (grid), to either red or blue. In order to win; no two rows and columns can be the same, a full row or column must have an equal amount of blue and red tiles, and three of the same colors cannot be placed next to each other (horizontally or vertically).

I have a working interface, timer, and event listeners/handlers for each button. A single click changes a tile to red, a double click changes the tile to blue. According to the rules of the game, a randomly pre-selected number of tiles (no less than 4 and no more than 5 total, and no more than 2 in each row or column) must already be set to red or blue by the computer, each time a game is instantiated. I am at my wit’s end trying to solve for how to write this logic. Help would be much appreciated. Here is my code thus far:

// Minutes and seconds
let currentMinute = document.getElementById("current-minute");
let currentSecond = document.getElementById("current-second");

let buttons = document.querySelector(".buttons");

// Row 1
let r1c1 = document.getElementById("row1-col1");
let r1c2 = document.getElementById("row1-col2");
let r1c3 = document.getElementById("row1-col3");
let r1c4 = document.getElementById("row1-col4");

// Row 2
let r2c1 = document.getElementById("row2-col1");
let r2c2 = document.getElementById("row2-col2");
let r2c3 = document.getElementById("row2-col3");
let r2c4 = document.getElementById("row2-col4");

// Row 3
let r3c1 = document.getElementById("row3-col1");
let r3c2 = document.getElementById("row3-col2");
let r3c3 = document.getElementById("row3-col3");
let r3c4 = document.getElementById("row3-col4");

// Row 4
let r4c1 = document.getElementById("row4-col1");
let r4c2 = document.getElementById("row4-col2");
let r4c3 = document.getElementById("row4-col3");
let r4c4 = document.getElementById("row4-col4");

//Timer
let seconds = 0;
const timer = (val) => {
  return val > 9 ? val : "0" + val;
};

setInterval(() => {
  currentMinute.innerHTML = timer(parseInt(seconds / 60, 10));
  currentSecond.innerHTML = timer(++seconds % 60);
}, 1000);

timer();

// Tile matrix
let matrix = [
  [r1c1, r1c2, r1c3, r1c4],
  [r2c1, r2c2, r2c3, r2c4],
  [r3c1, r3c2, r3c3, r3c4],
  [r4c1, r4c2, r4c3, r4c4],
];

// Instantiate a new instance of the board each time the game is loaded
class GameBoard {
  constructor(matrix) {
    this.matrix = matrix;
  };

// Currently, this method randomly sorts the tiles in each row
  createMatrix(matrix) {
    matrix = this.matrix;

    for (let k = 0; k < matrix.length; k++) {
      let i = matrix[k].length;
      if (i == 0) return false;
      else {
        while (--i) {
          let j = Math.floor(Math.random() * (i + 1));
          let tempi = matrix[k][i];
          let tempj = matrix[k][j];
          matrix[k][i] = tempj;
          matrix[k][j] = tempi;
        };
      };
    };
    return matrix;
  };
};

// Single-click Event Handlers - Row 1
const r1c1_singleClick = () => {
  r1c1.style.backgroundColor = "red";
};
const r1c2_singleClick = () => {
  r1c2.style.backgroundColor = "red";
};
const r1c3_singleClick = () => {
  r1c3.style.backgroundColor = "red";
};
const r1c4_singleClick = () => {
  r1c4.style.backgroundColor = "red";
};

// Single-click Event Handlers - Row 2
const r2c1_singleClick = () => {
  r2c1.style.backgroundColor = "red";
};
const r2c2_singleClick = () => {
  r2c2.style.backgroundColor = "red";
};
const r2c3_singleClick = () => {
  r2c3.style.backgroundColor = "red";
};
const r2c4_singleClick = () => {
  r2c4.style.backgroundColor = "red";
};

// Single-click Event Handlers - Row 3
const r3c1_singleClick = () => {
  r3c1.style.backgroundColor = "red";
};
const r3c2_singleClick = () => {
  r3c2.style.backgroundColor = "red";
};
const r3c3_singleClick = () => {
  r3c3.style.backgroundColor = "red";
};
const r3c4_singleClick = () => {
  r3c4.style.backgroundColor = "red";
};

// Single-click Event Handlers - Row 4
const r4c1_singleClick = () => {
  r4c1.style.backgroundColor = "red";
};
const r4c2_singleClick = () => {
  r4c2.style.backgroundColor = "red";
};
const r4c3_singleClick = () => {
  r4c3.style.backgroundColor = "red";
};
const r4c4_singleClick = () => {
  r4c4.style.backgroundColor = "red";
};

// Single-click Event Listeners - Row 1
r1c1.addEventListener("click", r1c1_singleClick);
r1c2.addEventListener("click", r1c2_singleClick);
r1c3.addEventListener("click", r1c3_singleClick);
r1c4.addEventListener("click", r1c4_singleClick);
// Single-click Event Listeners - Row 2
r2c1.addEventListener("click", r2c1_singleClick);
r2c2.addEventListener("click", r2c2_singleClick);
r2c3.addEventListener("click", r2c3_singleClick);
r2c4.addEventListener("click", r2c4_singleClick);
// Single-click Event Listeners - Row 3
r3c1.addEventListener("click", r3c1_singleClick);
r3c2.addEventListener("click", r3c2_singleClick);
r3c3.addEventListener("click", r3c3_singleClick);
r3c4.addEventListener("click", r3c4_singleClick);
// Single-click Event Listeners - Row 4
r4c1.addEventListener("click", r4c1_singleClick);
r4c2.addEventListener("click", r4c2_singleClick);
r4c3.addEventListener("click", r4c3_singleClick);
r4c4.addEventListener("click", r4c4_singleClick);

// Double-click Event Handlers - Row 1
const r1c1_doubleClick = () => {
  r1c1.style.backgroundColor = "blue";
};
const r1c2_doubleClick = () => {
  r1c2.style.backgroundColor = "blue";
};
const r1c3_doubleClick = () => {
  r1c3.style.backgroundColor = "blue";
};
const r1c4_doubleClick = () => {
  r1c4.style.backgroundColor = "blue";
};

// Double-click Event Handlers - Row 2
const r2c1_doubleClick = () => {
  r2c1.style.backgroundColor = "blue";
};
const r2c2_doubleClick = () => {
  r2c2.style.backgroundColor = "blue";
};
const r2c3_doubleClick = () => {
  r2c3.style.backgroundColor = "blue";
};
const r2c4_doubleClick = () => {
  r2c4.style.backgroundColor = "blue";
};

// Double-click Event Handlers - Row 3
const r3c1_doubleClick = () => {
  r3c1.style.backgroundColor = "blue";
};
const r3c2_doubleClick = () => {
  r3c2.style.backgroundColor = "blue";
};
const r3c3_doubleClick = () => {
  r3c3.style.backgroundColor = "blue";
};
const r3c4_doubleClick = () => {
  r3c4.style.backgroundColor = "blue";
};

// Double-click Event Handlers - Row 4
const r4c1_doubleClick = () => {
  r4c1.style.backgroundColor = "blue";
};
const r4c2_doubleClick = () => {
  r4c2.style.backgroundColor = "blue";
};
const r4c3_doubleClick = () => {
  r4c3.style.backgroundColor = "blue";
};
const r4c4_doubleClick = () => {
  r4c4.style.backgroundColor = "blue";
};

// Double-click Event Listeners - Row 1
r1c1.addEventListener("dblclick", r1c1_doubleClick);
r1c2.addEventListener("dblclick", r1c2_doubleClick);
r1c3.addEventListener("dblclick", r1c3_doubleClick);
r1c4.addEventListener("dblclick", r1c4_doubleClick);
// Double-click Event Listeners - Row 2
r2c1.addEventListener("dblclick", r2c1_doubleClick);
r2c2.addEventListener("dblclick", r2c2_doubleClick);
r2c3.addEventListener("dblclick", r2c3_doubleClick);
r2c4.addEventListener("dblclick", r2c4_doubleClick);
// Double-click Event Listeners - Row 3
r3c1.addEventListener("dblclick", r3c1_doubleClick);
r3c2.addEventListener("dblclick", r3c2_doubleClick);
r3c3.addEventListener("dblclick", r3c3_doubleClick);
r3c4.addEventListener("dblclick", r3c4_doubleClick);
// Double-click Event Listeners - Row 4
r4c1.addEventListener("dblclick", r4c1_doubleClick);
r4c2.addEventListener("dblclick", r4c2_doubleClick);
r4c3.addEventListener("dblclick", r4c3_doubleClick);
r4c4.addEventListener("dblclick", r4c4_doubleClick);
body {
    background-image: url("Circuit-Space.webp");
    background-color: rgb(41, 38, 38);
    background-size: cover;

    font-family: 'Orbitron', sans-serif;
}


p {
    color: white;
}

h1 {
    position: relative;
    margin-left: 700px;
    margin-right: 700px;
    box-shadow: 0px 10px 20px black;
    border-radius: 10px;

    bottom: 5px;
    color: white;
}

.content {
    background-color: rgb(0, 0, 0);
    height: 600px;
    width: 50%;
    box-shadow: 0px 10px 20px red;

    position: relative;
    bottom: 5px;
    border-radius: 20px;
    opacity: 97%;
}

.buttons {
    position: relative;
    top: 25px;

    background-color: rgb(24, 33, 33);

    height: 100px;
    width: 100px;
    border-radius: 10px;
    margin: 1px;
}

.buttons:hover {
    box-shadow: 0px 0px 5px red;
}

#best-time {
    display: inline-flex;
    position: relative;
    color: black;
    top: 10px;
}

.current-time {
    display: inline-flex;
    position: relative;
    top: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="BitGo.css">
    <script src="BitGo.js" async></script>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@500&display=swap" rel="stylesheet">

    <title>BitGo</title>
</head>

<center>
<body>

    <header>
        <h1>BitGo</h1>
    </header>

    <div class="content">
        <p id="best-time">
            0:00
        </p>

        <br>

        <button class="buttons" id="row1-col1"></button>
        <button class="buttons" id="row1-col2"></button>
        <button class="buttons" id="row1-col3"></button>
        <button class="buttons" id="row1-col4"></button>

        <br>

        <button class="buttons" id="row2-col1"></button>
        <button class="buttons" id="row2-col2"></button>
        <button class="buttons" id="row2-col3"></button>
        <button class="buttons" id="row2-col4"></button>

        <br>

        <button class="buttons" id="row3-col1"></button>
        <button class="buttons" id="row3-col2"></button>
        <button class="buttons" id="row3-col3"></button>
        <button class="buttons" id="row3-col4"></button>

        <br>

        <button class="buttons" id="row4-col1"></button>
        <button class="buttons" id="row4-col2"></button>
        <button class="buttons" id="row4-col3"></button>
        <button class="buttons" id="row4-col4"></button>

        <br>

        <p class="current-time" id="current-minute">0</p>
        <p class="current-time">:</p>
        <p class="current-time" id="current-second">0</p>
    </div>
</body>
</center>

</html>

How to iterate through list of items in React list using arrow keys

I’ve seen similar posts on this issue, but when I try to implement what they suggested, it never works. I have the active state and my search results that are return on dispatch. When I type into the input search or click on it the menu opens below it and shows the results, yet when I hit the arrow keys it stays within the input bar and does not iterate/focus through each list item. I would like to make it so that when I hit either the down or up arrow key it would iterate through the search results and I can hit enter on any of them to trigger the search.

  const [active, setActive] = useState(0)
  const searchResults = useSelector((state) => Object.values(state.searchReducer.Search))

  const keyDown = (e) => {
    if(e.key === 38 && searchResults.length > 0){
      setActive(active - 1)
    }else if(e.key === 40 && active < searchResults.length - 1){
      setActive(active + 1)
    }
  }

 <BsSearch className="search-icon" />
      <form onSubmit={handleSubmit}>
      <input
        onClick={() => setMenu(true)}
        className="search-input"
        autoFocus
        onKeyDown={keyDown}
        type="search"
        placeholder="Search"
        onChange={(e) => setSearchVal(e.target.value)}
        value={searchVal}
      />
      </form>
      {menu && (
        <div className="search-cont">
          {searchResults.length > 0 ? (
            searchResults?.map((ele, i) => {
              return (
                <NavLink onClick={(() => {setSearchVal('')})}  key={i}  className="spot- 
                 links" to={`/users/${ele.id}`}>
                  <div
                    className="search-results-list"
                    id={active === i ? 'active' : null}
                  >
                    {ele.username}
                  </div>
                </NavLink>
              );
            })
    ```