why i cant access “fullName” from my object

class PersonCl {
  constructor(fullName, birthYear) {
    this.fullName = fullName;
    this.birthYear = birthYear;
  }

  // Methods will be added tp .prototype property
  calcAge() {
    console.log(2037 - this.birthYear);
  }

  get age() {
    return 2037 - this.birthYear;
  }
  set fullName(name) {
    if (name.includes(' ')) this._fullName = name;
    else alert(`${name} is not a full name`);
  }
}

const jessica = new PersonCl('jessica Davis', 1996);

i made an class and try to set the setter of exact name so it shows me error “maximize call stack” and now i changed the variable name but the original “firstName” is missing I know you can fix it with with the getter but i wanna know what the reason behind it I don’t need solution i need explanation from you guys

Bluring a content on a website during screenshots/recordings

I’ve been coding a messenger, and a few days ago I came across netflix’s protection against screnshots and screen recordings, and I wonder, how did they do it? I tried searching it online, read a bunch of forums, but found nothing, and everyone says that this is impossible, though netflix has it, and it works in most cases. I’ve got spring boot/security backend, and angularjs frontend for my website. Does anyone know how to implement this mechanic into a website?

Why is my rest client giving me this error?

im getting an error when trying to send request on my rest file, it says: The connection was rejected. Either the requested service isn’t running on the requested server/port, the proxy settings in vscode are misconfigured, or a firewall is blocking requests. Details: RequestError: connect ECONNREFUSED 127.0.0.1:30001.

i tried to send request, i expected the rest client response to pop up showing the users information this is a tutorial i was following and at the 12:04 minute he clicks send request and this is what pops up, thats what i need but isnt happening

How do you modify an array in React state with a callback function and map through every element

I have have an array defined in state for the first render. I’m trying to modify the array using a callback function that react automatically calls and provides the current state value for to ultimately map through every element but i’m receiving this error “Cannot read properties of undefined (reading ‘map’)”

let initialShapes = [
  { id: 0, type: 'circle', x: 50, y: 100 },
  { id: 1, type: 'square', x: 150, y: 100 },
  { id: 2, type: 'circle', x: 250, y: 100 },
];


export default function App() {
  const [shapes, setShapes] = useState(initialShapes);

  function handleClick() {
    

    setShapes(function(prevData) {
      prevData.map(prev => {
        return {
          ...prev,
          y: prev.y + 50
        }
    })
    });
  }

I tried using a callback function and map the callback value which is supposed to be an array but I’m receing this error “Cannot read properties of undefined (reading ‘map’)”

Is there any possibility to make my chrome extension read and write directly from and to a local spreadsheet in my file system?

It seems that using file system API is not working any more with extensions, i have created a chrome extension that need to collect data from user interaction with the extension and send it to a spreadsheet in my local file system, and need to read data from the same spreadsheet when the user needs, my question now is not about code, it seems that most APIs not working any more to make extensions communicate with file system or at least what i have tried,i have an alternative to move everything to google sheets and make my extensions write and read from it but i wonder is there any way or API to make extensions able to read and write to local file system instantly without downloading the updated file every time i make an update?

I cannot get the Datatable.net Bootstrap 5 example to work when populating the data in the table from a CSV file

I am trying to create a web app to show csv data into an html table, I was following the instructions on datatables.net for their bootstrap 5 styling in the Datatables.net bootstrap 5 link. I had some trouble getting the example to work, I got help from a stack overflow member to fix my issues. Now that I was able to run the example code, I am trying to use a csv file as my data source to create the table and apply the bootstrap 5 styling. code runs with no error in console but I am not getting the end result of pagination and data filtering as shown in the example. I cant figure out what I am doing wrong here.

This is the data in my csv file

Name;Position;Office;Age;Start date;Salary
Tiger Nixon;System Architect;Edinburgh;61;2011-04-25 ;$320,800
Garrett Winters;Accountant;Tokyo;63;2011-07-25;$170,750
Ashton Cox;Junior;San Francisco;66;2009-01-12;$86,000

This is my html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Table</title>
    <link rel="stylesheet" href="CSS/bootstrap.min.css">
    <link rel="stylesheet" href="CSS/dataTables.bootstrap5.min.css">
</head>
<body>
<div class="container">
        <h3>Upload a CSV file to display in Bootstrap Table</h3>
        <!-- Input element to upload an csv file -->
        <input type="file" id="file_upload" />
        <button onclick="upload()" class="btn btn-primary">Upload</button>  
        <br>
        <br>
</div>
        <!-- table to display the csv data -->

<table id="data-table" class="table table-striped" style="width:100%"></table>

<script defer src="SCRIPTS/scripts.js"></script>
<script defer src="SCRIPTS/jquery-3.5.1.js"></script> 
<script defer src="SCRIPTS/jquery.dataTables.min.js"></script> 
<script defer src="SCRIPTS/dataTables.bootstrap5.min.js"></script>    
<script defer src="SCRIPTS/app.js"></script>
</body>
</html>

The scripts.js file has the following code to load the csv data

      // Method to upload a valid csv file
      function upload() {
        var files = document.getElementById('file_upload').files;
        if(files.length==0){
          alert("Please choose any file...");
          return;
        }
        var filename = files[0].name;
        var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
        if (extension == '.CSV') {
            //Here calling another method to read CSV file into json
            csvFileToJSON(files[0]);
        }else{
            alert("Please select a valid csv file.");
        }
      }
       
      //Method to read csv file and convert it into JSON 
      function csvFileToJSON(file){
          try {
            var reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function(e) {
                var jsonData = [];
                var headers = [];
                var rows = e.target.result.split("rn");               
                for (var i = 0; i < rows.length; i++) {
                    var cells = rows[i].split(";");
                    var rowData = {};
                    for(var j=0;j<cells.length;j++){
                        if(i==0){
                            var headerName = cells[j].trim();
                            headers.push(headerName);
                        }else{
                            var key = headers[j];
                            if(key){
                                rowData[key] = cells[j].trim();
                            }
                        }
                    }
                     
                    if(i!=0){
                        jsonData.push(rowData);
                    }
                }
                  
                //displaying the json result into HTML table
                displayJsonToHtmlTable(jsonData);
                }
            }catch(e){
                console.error(e);
            }
      }
       
      //Method to display the data in HTML Table
      function displayJsonToHtmlTable(jsonData){
        var table=document.getElementById("data-table");
        if(jsonData.length>0){
            var headers = Object.keys(jsonData[0]);
            var htmlHeader='<thead><tr>';
             
            for(var i=0;i<headers.length;i++){
                htmlHeader+= '<th>'+headers[i]+'</th>';
            }
            htmlHeader+= '<tr></thead>';
             
            var htmlBody = '<tbody>';
            for(var i=0;i<jsonData.length-1;i++){
                var row=jsonData[i];
                htmlBody+='<tr>';
                for(var j=0;j<headers.length;j++){
                    var key = headers[j];
                    htmlBody+='<td>'+row[key]+'</td>';
                }
                htmlBody+='</tr>';
            }
            htmlBody+='</tbody>';
            var htmlfooter='<tfoot><tr>';
             
            for(var i=0;i<headers.length;i++){
                htmlfooter+= '<th>'+headers[i]+'</th>';
            }
            htmlfooter+= '<tr></tfoot>';
            table.innerHTML=htmlHeader+htmlBody+htmlfooter;
        }else{
            table.innerHTML='There is no data in CSV';
        }
      }
  

and finally app.js file is as shown below

new DataTable('#data-table');

loop my rock paper scissors game five times and update score counters

I’ve been trying to get my game to loop for five rounds and update the score variables then display stats at the end but I’m stuck.

I can’t figure out why the while loop is not working, I tried moving it to enclose different portions of he game body, I’ve even enclosed the entire game() function and still it’s a no go.

where am I going wrong?

JavaScript

//button control logic
let buttons = document.querySelectorAll('button');
buttons.forEach(button => {
    button.onclick = game;
});

   //introduction
   alert("Get ready! five rounds! -rock- -paper- -scissors- Gong yea tam-pei!!!")

//game body
function game() {
    let round = 0;
let draws = 0;
let computerScore = 0;
let playerScore = 0;

    //get user choice
    let playerOp = this.id;
    alert(`player: "${playerOp}"`); //alert response

    //get computer choice
    let computerOp = Math.floor(Math.random() * 3);
    if (computerOp === 0) {
        computerOp = 'rock';
    } else if (computerOp === 1) {
        computerOp = 'paper';
    } else {
        computerOp = 'scissors';
    };
    alert(`computer: "${computerOp}"`);//alert computer choice
    
    //five round loop
    while(round < 5){
    function playRound(playerOp, computerOp) {

        let display = document.querySelector('.display');//reference html display area 

        if (computerOp === playerOp) { //if both players pick the same value
            draws++;
            display.textContent = 'It's a draw!';

        } else if (computerOp == 'rock' && playerOp == 'scissors' || //computer win logic
            computerOp == 'paper' && playerOp == 'rock' ||
            computerOp == 'scissors' && playerOp == 'paper') {
            computerScore++;
            display.textContent = `${computerOp} beats ${playerOp}, computer: ${computerScore}`;//update display

        } else if (playerOp == 'rock' && computerOp == 'scissors' || //player win logic
            playerOp == 'paper' && computerOp == 'rock' ||
            playerOp == 'scissors' && computerOp == 'paper') {
            playerScore++;
            display.textContent = `${playerOp} beats ${computerOp}, player: ${playerScore}`;//update display
        }
}
//5 count incrementer
}round++
 return playRound(playerOp, computerOp);
}

    /*
if(rounds === 5){
    display.textContent = `You have won ${playerScore}
                           times,draw ${draws} times and lost 
                           ${computerScore} times.`

*/

Html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Rock > Paper > Scissors</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div class="container">
        <span id="btn-wrap">
            <button id="rock">ROCK</button>
            <button id="paper">PAPER</button>
            <button id="scissors">SCISSORS</button>
        </span>

            <div class="display"></div>
        </div>
        
        <script src="scripts.js" async defer></script>
    </body>
</html>

Dop down list with the style of an range

Without use app script (i want make my sheet lighter), how i can set a drop down style on a define plage ? Like we can define the values from this way but how about the style ? I need to do this because i use this range for different things.

Thank you in advance ^^

(Vue.js) TypeError: Cannot read properties of undefined (reading ‘map’)

I want to send sampleId from my Vue.js frontend page to the backend. However, as I press the sending button, the error pops up it says that my sample.module.js file has a problem. Can anyone help me with the problem?

The entire error looks like this below:

vue.runtime.esm.js:1887 TypeError: Cannot read properties of undefined (reading 'map')
    at Store.getSampleResultRequest (samples.module.js:64:47)
    at wrappedMutationHandler (vuex.esm.js:748:13)
    at commitIterator (vuex.esm.js:400:7)
    at Array.forEach (<anonymous>)
    at eval (vuex.esm.js:399:11)
    at Store._withCommit (vuex.esm.js:530:3)
    at Store.commit (vuex.esm.js:398:8)
    at Store.boundCommit [as commit] (vuex.esm.js:343:19)
    at local.commit (vuex.esm.js:700:13)
    at Store.getSampleResult (samples.module.js:21:9)

The frontend Vue.js page that I send sampleId is like this below:

<template>
    <div>
        <p>
            <router-link to="/">Home Page</router-link>
            <router-link to="/login">Logout</router-link>
        </p>
        <form @submit.prevent="handleSubmit">
            <h2 class="getSampleResult">Get Sample Result</h2>
            <div class="form-group">
                <label for="sampleId">Sample Id</label>
                <input type="text" v-model="sample.sampleId" name="sampleId" v-validate="'required'" class="form-control" :class="{ 'is-invalid': submitted && errors.has('sampleId') }" />
                <div v-if="submitted && errors.has('sampleId')" class="invalid-feedback">{{ errors.first('sampleId') }}</div>
            </div>
            <div class="form-group">
                <button class="btn btn-primary" @click="getSampleResult(sample.id)">Get Sample result</button>
                <img v-show="sample.gettingResult" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
            </div>
        </form>

    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
    data () {
        return {
            sample:{
                sampleId: 0
            },
            submitted: false
        }
    },
    created () {
        this.getAllSamples();
    },
    computed: {
        ...mapState({account: state => state.account, users: state => state.users.all, samples: state => state.samples.all}) 
    },
    methods: {
        ...mapActions('samples', {
            getSampleResult: 'getSampleResult',
            getAllSamples: 'getAllSamples'
        }),
        handleSubmit (e) {
            this.submitted = true;
            this.getSampleResult(this.sample.sampleId);
        }
    }
};
</script>
<style scoped>
.newSample{
    color:blue
}
form{
    background-color:rgb(218,226,249);
    color:black;
    width: 400px;
    margin-top: 300px;
    margin-left: 200px;
}
input[type="text"], input[type="password"] {
    margin: 8px 0;
    width: 200px;
}

</style>

The sample.module.js file looks like this:

import { sampleService } from '../_services';
const state = {
    all: {}
};
const actions = {
    getSampleResult({commit}, id){
        commit('getSampleResultRequest', id);
        sampleService.getSampleResult(id).then(
            sample => commit('getSampleResultSuccess', id),
            error => commit('getSampleResultFailure', {id, error: error.toString()})
        );
    },
    getAllSamples({commit}){
        commit('getAllSampleRequest');
        sampleService.getAllSamples().then(
            sample => commit('getAllSampleSuccess', sample),
            error => commit('getAllSampleFailure', error)
        );
    },
    addNewSample({dispatch, commit}, sample){
        commit('addNewSampleRequest', sample);
        sampleService.addNewSample(sample).then(
            sample => {
                commit('addNewSampleSuccess', sample)
            },
            error => {
                commit('addNewSampleFailure', error);
                dispatch('alert/error', error, { root: true });
            }
        )
    }
}

const mutations = {
    getAllSampleRequest(state) {
        state.all = { loadingSamples: true };
    },
    getAllSampleSuccess(state, samples) {
        state.all = { samples: samples };
        console.log(state);
    },
    getAllSampleFailure(state, error) {
        state.all = { error };
    },
    getSampleResultRequest(state, id) {
        state.all.samples = state.all.samples.map(sample =>
            sample.sampleId === id
                ? { ...sample, getSampleResult: true }
                : sample
        )
        console.log(state);
    },
    getSampleResultSuccess(state, id) {
        state.all.samples = state.all.samples.filter(sample => sample.sampleId === id)
    },
    getSampleResultFailure(state, {id, error}) {
        state.all.samples = state.samples.map(sample => {
            if (sample.sampleId !== id) {
                // make copy of user without 'deleting:true' property
                const { deleting, ...sampleCopy } = sample;
                // return copy of user with 'deleteError:[error]' property
                return { ...sampleCopy, deleteError: error };
            }

            return sample;
        })     
    },
    // getSampleIdRequest(state, sample){
    //     state.status = {getSampleId: true};
    //     state.sample = sample;
    // },
    // getSampleIdSuccess(state, sample){
    //     state.status = {getSampleId: true};
    //     state.sample = sample;
    // },
    // getSampleIdFailure(state, {id, error}){
    //     state.status = {};
    //     state.sample = null;
    // },
    addNewSampleRequest(state, sample) {
        state.sample = sample;
    },
    addNewSampleSuccess(state, sample) {
        state.sample = sample;
    },
    addNewSampleFailure(state, error) {
        state.sample = null;
    }
};

export const samples = {
    namespaced: true,
    state,
    actions,
    mutations
};

Error in the classic Rock,Paper, Scissors game using javascript

const doRunGame = confirm(“Hello, Would you like to play n Rock, Paper And Scissors?”);

if (doRunGame) {

while (true) {

let playerChoice=getPlayerChoice();

let computerChoice=getComputerChoice();

let result=evaluateResult(playerChoice,computerChoice,);

displayResult(playerChoice,computerChoice,result);

let doRerun = confirm(“Would you like to play again? “);

if (doRerun) {

continue;

}

else{

exit();

break;

}

}

}

else{

exit();

}

function getPlayerChoice() {

let playerChoice = prompt(“Enter Rock,Paper or Scissors”);

playerChoice=playerChoice.trim().toLowerCase()

if(playerChoice===”rock”||playerChoice===”paper”||playerChoice===”scissors”){

return playerChoice;

}

else {

alert("Sorry,You didn't write Rock,Paper or Scissors");

}

}

function getComputerChoice() {

const options = [“rock”,”paper”,”scissors”];

let computerChoice = options[Math.floor(Math.random()* options.length)]

return computerChoice;

}

function evaluateResult(playerChoice,computerChoice) {

if (playerChoice===computerChoice) {

return result="It's a tie";

}

else if (playerChoice===”rock”) {

switch (computerChoice) {

  case 'scissors':

    return result="You won";

    break;

  case 'paper':

    return result="You lost"

    break;

}  

}

else if (playerChoice===”paper”) {

switch (computerChoice) {

  case 'rock':

    return result="You won";

    break;

  case 'scissors':

    return result="You lost";

    break;

}

}

else if (playerChoice===”scissors”) {

switch (computerChoice) {

  case 'paper':

    return result="You won";

    break;

  case 'rock':

    return result="You lost";

    break;

}

}

}

function displayResult(playerChoice,computerChoice,result) {

alert(You chose ${playerChoice}, Computer chose ${computerChoice} And ${result});

}

function exit () {

alert(“Maybe next time”)

}

I tried to create the rock paper scissors game using javascript,the problem I’m having is that if i click the cancel button when asked ” would you like to play rock paper scissors ?” The alert message displays”may be next time” as expected but it asks again “would you like to play…” When i click cancel again the program runs as expected and it proceeds to console

New to TypeScript, Errors converting JS to TS learning as I go

Im converting an existing Reactjs project to typescript. Im also learning TS as I go on this project. I am getting a few errors that I am not sure how to navigate and cant seem to find a good answer on google.

One of my errors, I am pulling a useState boolean from my useContext into my protected route:

Property ‘loggedIn’ does not exist on type ‘{}’.

Protected Route:

import { Navigate } from "react-router-dom";
import { useAuthContext } from "../context/AuthContext";
import { ReactNode } from "react";

// type ProtectedRouteProps = {
//   children: ReactNode;
// };

export const ProtectedRoute = ({ children }: any) => {
  const { loggedIn } = useAuthContext();
  if (!loggedIn) {
    // user is not authenticated
    return <Navigate to="/" />;
  }
  return children;
};

My AuthContext:

import { useState, createContext, useContext, ReactNode } from "react";
import { useNavigate } from "react-router-dom";

const AuthContext = createContext({});

export function useAuthContext() {
  return useContext(AuthContext);
}
type AuthProviderProps = {
  children: ReactNode;
};

export function AuthProvider({ children }: AuthProviderProps) {
  const [loggedIn, setLoggedIn] = useState<boolean>(
    localStorage.getItem("loggedIn") === "true"
  );

  const [selectedDogs, setSelectedDogs] = useState<number[]>([]);
  const navigate = useNavigate();

  function setDogMatch(data: number[]) {
    setSelectedDogs(data);
    navigate("/dog-match");
  }

  return (
    <AuthContext.Provider
      value={{
        loggedIn,
        setLoggedIn,
        selectedDogs,
        setDogMatch,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
}

Not sure what I am missing for that type and where it would need to be set if in my AuthContext or Protected Route.

I also created another error myself my SearchFilter.tsx. Error:

Property ‘map’ does not exist on type ‘string | number’.
Property ‘map’ does not exist on type ‘string’.

Heres my SearchFilter.tsx not sure what to do with that map type error. :

import Select from "react-select";

type Props ={
  props: string | number
  data: string | number
  name: string
}

export default function SearchFilters(props: Props) {
  const options =
    props.data &&
    props.data.map((data: Props) => {
      return { value: data, label: data };
    });

  return (
    <div className="dropdown-container">
      <h4>{props.name}</h4>
      <Select options={options} isSearchable={true} {...props} />
    </div>
  );
}

Thanks for the help new to TypeScript and learning as I go on this project!

Stacking Different View in React-Native Failed

I am attempting to implement a page in react-native with a Map component on the botton, and I am also trying to put a overlapping scroll view on top of the Map view without influencing the functionality of it. However, I am having trouble making this work. Currently I made it so that if the List is commented out the map could be displayed without any error, but once the list is added it got pushed all the way up and no longer display properly.

This is my Bottom Map component

<View style={styles.container}>
        <TouchableOpacity style={styles.button} onPress={openModal}>
          <Text style={styles.buttonText}>Find Place</Text>
        </TouchableOpacity>

        <Modal
          visible={modalVisible}
          animationType="slide"
          transparent={false}
          style={styles.modal}
        >
          <View>
            <TextInput
              style={styles.input}
              placeholder="Search the Type of Restaurant here"
              value={search}
              onChangeText={setSearch}
              onSubmitEditing={handleSearch}
            />
            <Button title="Close Modal" onPress={closeModal} />
          </View>
        </Modal>
        
        <MapView
          style = {styles.map}
          region = {curRegion}
        >
          {markers}
          <Marker
            coordinate={{ latitude: 36.143, longitude: -86.8 }}
            title="Marker 2"
          />
        </MapView>
       
        
    </View>

This is my scrollView

<Animated.ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={{
          paddingBottom: 200,
          backgroundColor: 'transparent',
          marginTop: -100,
        }}
        onScroll={Animated.event(
      [{ nativeEvent: { contentOffset: { y: scrollY } } }],
      { useNativeDriver: true },
      () => { },          // Optional async listener
    )}
    style={[{ paddingTop: imageHeight }]}> 
    <Animated.View style={[
      styles.block,
      {
        borderTopLeftRadius: animateBorderRadius,
        borderTopRightRadius: animateBorderRadius
      }
    ]}>
      <Text>Hello</Text>
      <Text>World</Text>
    </Animated.View>
    <View style={{ height: 0.4 * deviceHeight }}></View>
  </Animated.ScrollView>

How I use them together

<View style={styles.container}> 
  <SafeAreaView style = {{flex : 1}}>
    <Map style={styles.theMap}/>
    <List
      scrollY={scrollY}
      style = {styles.scrollView}
    />
  </SafeAreaView>
 </View>

I attempted to use zAxis, and making the map absolute position and assign a height but they all failed.

How do you create a unique key within a 2D array using React and JavaScript for a chessboard

I am new to building applications and coding, as a side project I am trying to make a chessboard with react and JavaScript. I am currently stuck trying to figure out a way to make a unique id key inside the 2D for loop in the Chessboard component below:

Here is the code for the Tile component

import './Tile.css';

const WhiteTile = () =>
{
   return(
      <div className='TileWhite'></div>
   )
}

const AquaTile = () =>
{
   return(
      <div className='TileAqua'></div>
   )
}


const ENUM_OBJECT = 
{
   whiteTile: <WhiteTile/>,
   aquaTile: <AquaTile/>,
};

function Tile({tileType}) 
{
   return ENUM_OBJECT[tileType]
}

export default Tile;

this is the code for the Chessboard component

import React from 'react';  
import '../ChessBoard/Chessboard.css'
import Tile from './Tile';



function ChessBoard()
{  
    const xCoordinates = ["a", "b", "c", "d", "e", "f", "g", "h", "0"];


    const yCoordinates = ["0", "1", "2", "3", "4", "5", "6", "7", "8"];
    
    const coordinatesBoard = []; 

    const RenderCoordinates = () =>
    {

        for(let y = yCoordinates.length; y > 0; y--)
        {
            for(let x = 0; x < xCoordinates.length - 1; x++)
            {   
                if(x % 2 === 0)
                {
                    coordinatesBoard.push(<Tile tileType={"whiteTile"} key={''}></Tile>);
                }
                else
                {
                    coordinatesBoard.push(<Tile tileType={"aquaTile"} key={''}></Tile>);

                }
            }
        }
        return coordinatesBoard; 
    }


    return(<div className="App">
            {<RenderCoordinates/>}
            </div>)
    
}

export default ChessBoard; 

I tried using a map function earlier


 const RenderTiles = () =>
    {
        const cBoard = coordinatesBoard.map((xyCoordinates, index) =>
        {
                if(index % 2)
                {
                    return(
                    <div className ="Tile1" key={index}>
                        {xyCoordinates}
                    </div>
                    )
                }
                else 
                {
                    return(
                    <div className ="Tile2" key={index}>
                        {xyCoordinates}
                    </div>
                    )
                }
        });

        return cBoard
    }

also looked into useState

    const [counter, setCounter] = useState(0);

    const increment = () => 
    {
    
        setCounter(counter + 1);
    }

Tried inserting counter in here but ran into an infinite loop(from the Chessboard function)

coordinatesBoard.push(<Tile tileType={"whiteTile"} key={counter + 1}></Tile>);

I was expecting the counter to increment every time a Tile was pushed on the Chessboard
pls help.

discord js bot crashing at specified time in future

I’m trying to edit the discord embed message by the bot itself at specified time. The embed message was sent as the response to the user command.

    function timeToTarget() {
        while (seed < new Date()) {
            seed.setDate(seed.getDate() + 1);
        }
        return Math.floor(seed.getTime() / 1000);
    }
    
    const duration = timeToTarget();

    const calculateTimeToEdit = duration * 1000;
    const editMsgDate = calculateTimeToEdit;

    const editMsg = EmbedBuilder.from(embedMsg).setDescription(`${user}, mmmm... `);

    setInterval(() => { // function ()
        if (editMsgDate <= Date.now()) {
            try {
                interaction.editReply({
                    embeds: [editMsg],
                    /* fetchReply: true */
                });
            }
            catch (error) {
                console.error(error);
            }
        }
    }, 3000);

Then at the specified date, the bot crashes with no errors in console. The bot is able to edit the message when I set the duration directly in ms. The duration is set everytime + 1 day in future and then there’s a countdown for it, function which is checking every 3 seconds if the date is <= Date.now(). So why the bot is crashing only, when the duration is the same as Date.now()?
Could it be reached max allocation memory limit or it’s something else?

Thanks for possible answers!

Google Chrome Web Serial API: Will it work after the computer go to sleep/idle?

I’m implementing a QR Code reader (via a Honeywell 7580g reader) for check-ins. This uses the reader as a serial connection, not as a keyboard input.

Users will show their QR Code to the reader, and then through the web serial connection, the app will get the code and check in (call an API).

I have a PoC in place that’s working. But I would like to confirm if this solution is feasible beyond the scope of a PoC or if I need to fallback to a desktop app instead.

  1. This only works if I keep the Chrome tab open. Is there a way to keep it working in the background even if the Chrome tab isn’t opened? Keeping the tab open can cause issues. Someone will eventually restart the host computer and forget that they need to open the browser and a specific page or mistakenly close the tab while navigating using the browser. Any ideas here?
  2. I noticed that it stopped working after the computer went to sleep. Can it continue to work even if the computer goes to sleep?

My use case is to keep reading from the serial port as in the background as possible. It won’t be just when users are doing something with the app.