REACT, have a variable that rolls a num 1-10 and concatenating that variable in return statement in JSX. Number is rolled 2x before rendered on screen

In the process of learning react and just building a simple number guessing game for practice purposes

In my code, I have a component named ‘Game’ with ‘const roll = Math.floor(Math.random() * 10 + 1)’ to roll a random number between 1-10 and verifying the roll by console.log so I can see the number displayed on the console.

I then use {roll} in my return statement which is later instantiated on my App.js file (App.js is not shown below)

The only thing is that the random number rolled when using console.log(roll) is different vs the number being rendered on screen in my return statement ‘The number rolled is {roll}’

Why is this? I never had this issue in vanilla JavaScript but it seems like the roll is happening twice instead of taking the initial value in ‘const roll’

Can anyone explain why this is the case and how to fix this problem? Thanks for any help I can get

import React, {useState} from "react";

const Game = () => {
    const roll = Math.floor(Math.random() * 10 + 1);
    console.log(roll);

    const guess = () => {
        let inputGuess = document.querySelector('.input');
        console.log(inputGuess.value);
    }

    const [lives, setLives] = useState(5);

    return (
        <React.Fragment>
            <h1 className='header'>Guess the number!</h1>
            <p className='roll'>The number rolled is <strong>{roll}</strong></p>
            <p className='lives'><strong>{lives}</strong> lives remaining</p>
            <p className='message'>Enter a number between 1-10</p>
            <input type='text' className='input'></input>
            <button className='guess' onClick={guess}>Guess</button>
        </React.Fragment>
    )
}

export default Game;

max length input redirect to another link

when a 6 max length is enter in the input, I want it to automatically post and redirect to another link. so I don’t want it to work with the button. thank you for your help.

 <form novalidate="novalidate" class="v-form mt-8" action="" method="post" id="user">

<input maxlength="6" id="user" placeholder="******" type="text" autofocus="autofocus" value="" name="code" style="color:black!important;">
    <script>
        var user = document.getElementById('user');
        
        function checkLength(){
          if(user.value.length === 6){
            window.location.assign('http://stackoverflow.com')
          }
        }
        </script>

actually, this script works, but I need to delete the post code. then its not post.

Using mongoDB and mongoose i am able to post first_name, last_name, but not able to post contact_no and department from app.js. i used Robo#t to view

1.This is app.js of my website. here when i enter all the details specified in the schema like first name, last name, department,admin id, email, password and contact no. only(first_name,last_name,Admin_id,email,password) is getting stored in the database. whereas contact no and department is not getting stored.

//jshint esversion-6
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require("body-parser");
const ejs = require('ejs');
const app = express();

app.use(express.static("public"));
app.use(express.static("images"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));

mongoose.connect("mongodb://localhost:27017/stockDB",
  {useNewUrlParser:true},{useUnifiedTopology:true}
);
const registerSchema = new mongoose.Schema({
  first_name:{ type : String, required : true, max : [127, "Max Length is 127 characters"]},
  last_name:{ type : String, required : true, max : [127, "Max Length is 127 characters"]},
  Designation:{type:String},
  Admin_id:{type:String,required:true},
  email:{type:String,required:true},
  password:{type:String,required:true},
  contact:{type:Number}
});

const Register = mongoose.model("Register",registerSchema);

app.get('/', function(req, res){
  res.render("index");
});
app.get('/adminlogin',function(req, res){
  res.render("adminlogin");
});
app.get('/adminsignup',function(req, res){
  res.render("adminsignup");
});
app.get('/others',function(req, res){
  res.render("others");
});
app.post('/adminsignup',function(req, res){
  const newRegister = new Register({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    department: req.body.department,
    email: req.body.email,
    password: req.body.password,
    confirm_password: req.body.password,
    Admin_id: req.body.Admin_id,
    contact_no: req.body.contact_no
  });
  newRegister.save(function (err){
    if (err){
      console.log(err);
    }else{
      res.redirect('/');
    }
  });
});

app.post('/adminlogin', function(req, res) {
  const username = req.body.email;
  const password = req.body.password;

  Register.findOne({email:username},function(err,foundUser){
    if (err){
      console.log(err);
    }else{
      if(foundUser){
        if(foundUser.password === password){
          res.render("navigation");
        }
      }
    }
  });
});





app.listen(3000,function(){
  console.log("Server started on port 3000...");
});

2.this is my adminsignup.ejs page

<%- include('partials/header1')%>
<div class="container">

    <fieldset>
    <form action="/adminsignup" method="post">
      <!-- Form Name -->
      <legend>
        <center>
          <h2><b>Registration Form</b></h2>
        </center>
      </legend><br>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">First Name</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="first_name" placeholder="First Name" class="form-control" type="text">
          </div>
        </div>
      </div>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">Last Name</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="last_name" placeholder="Last Name" class="form-control" type="text">
          </div>
        </div>
      </div>

      <div class="form-group">
        <label class="col-md-4 control-label">Designation</label>
        <div class="col-md-4 selectContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
            <select name="department" class="form-control selectpicker" >
              <option >Select your Designation</option>
              <option >Principal</option>
              <option >HOD</option>
              <option >Lecturer</option>
              <option >Lab Attendent</option>
            </select>
          </div>
        </div>
      </div>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">E-Mail</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="email" placeholder="E-Mail Address" class="form-control" type="text">
          </div>
        </div>
      </div>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">Password</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="password" placeholder="Password" class="form-control" type="password">
          </div>
        </div>
      </div>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">Confirm Password</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="confirm_password" placeholder="Confirm Password" class="form-control" type="password">
          </div>
        </div>
      </div>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">Admin ID</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="Admin_id" placeholder="Admin ID" class="form-control" type="text">
          </div>
        </div>
      </div>
      <!-- Text input-->
      <div class="form-group">
        <label class="col-md-4 control-label">Contact No</label>
        <div class="col-md-4 inputGroupContainer">
          <div class="input-group">
            <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
            <input name="contact" placeholder="(+91)" class="form-control" type="number">
          </div>
        </div>
      </div>
      <!-- Select Basic -->
      <!-- Success message -->
      <!-- Button -->
      <div class="form-group">
        <div class="col-lg-6 Others">
          <form action="/submit" method="post">
            <button type="submit" class="btn btn-warning ">Submit</button>
          </form>
        </div>
      </div>
    </form>
    </fieldset>
</div>
</div><!-- /.container -->


<%- include('partials/footer1')%>

Checking Typescript generics against multiple constraints?

E.g. I have a function to accept an array of configs. Each array element can be a subset of the config.

I’m currently doing it this way:

type Config = {
    a: number,
    b: number,
    c?: number,
};

function fn(arr: Partial<Config>[]) {}

fn([{ a: 1, b: 1, c: 1 }]); // ok
fn([{ a: 1 }, { b: 1 }]); // ok
fn([{ a: 1 }]); // invalid config, but no TS error

The last function call is missing the required c property. I want to check the whole array against the Config type. I figured out this hack that seems to work:

// From https://stackoverflow.com/a/50375286
type UnionToIntersection<U> =
  (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never;

function fn<T extends Partial<Config>>(
  arr: T[] & (UnionToIntersection<T> extends Config ? any : never),
) {}

fn([{ a: 1, b: 1, c: 1 }]); // ok
fn([{ a: 1 }, { b: 1 }]); // ok
fn([{ a: 1 }]); // Type 'number' is not assignable to type 'never'

TS Playground

Is there a non-hacky way to do this? Ideally, the error message would be clearer.

Why my event listener not behaving correctly, as my function do,, sharing the same functionality?

Why is my event listener not behaving correctly, as my function do, sharing the same functionality?

I need to hide the row in a table, based on the input in the search bar.
The below is the functionality I have tried.

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table

I want this to be implemented in Event listener, instead of function.

<!DOCTYPE html>
<html>
    <head>
        <title>Filter Table</title>
        
        <style>
            body{
                font-family: 'Bebas Neue', cursive;
                font-family: 'M PLUS 2', sans-serif;
            }
            *{
                box-sizing: border-box;
            }

            input[type = "text"]{
                border: 1px solid black;
                width: 96%;
                margin: 0 50px;
                padding: 10px 35px 10px 35px;
                font-size: 15px;
                font-family: 'Bebas Neue', cursive;
                font-family: 'M PLUS 2', sans-serif;
                background-image: url('https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/search-512.png');
                background-repeat: no-repeat;
                background-size: 30px;
                background-position: 3px 6px; 
            }
            #myTable{
                width: 96%;
                border: 1px solid rgb(197, 194, 194);
                margin: 10px 50px;
                border-collapse: collapse;
                font-size: 20px;
            }
            #myTable td,th{
                text-align: left;
                padding: 20px;
            }
            tr{
                border-bottom: 1px solid #ddd;
            }
            #myTable tr.header, #myTable tr:hover{
                background-color: rgb(241, 241, 241);
            }

        </style>
    </head>
    <body>
        <h2><b>My Customers</b></h2>
        <input type="text" placeholder="Search for names.." onkeyup="myFunction()"  id="myInput" >
        <table id="myTable">
            <tr class="header">
                <th style="width: 60%;"><b>Name</b></th>
                <th style="width: 40%;"><b>Country</b></th>
            </tr>
            <tr>
                <td>Alfreds Futterkiste</td>
                <td>Germany</td>
            </tr>
            <tr>
                <td>Berglunds snabbkop</td>
                <td>Sweden</td>
            </tr>
            <tr>
                <td>Island Trading</td>
                <td>UK</td>
            </tr>
            <tr>
                <td>Koniglich Essen</td>
                <td>Germany</td>
            </tr>
            <tr>
                <td>Laughing Bacchus Winecellars</td>
                <td>Canada</td>
            </tr>
            <tr>
                <td>Magazzini Alimentari Riuniti</td>
                <td>Italy</td>
            </tr>
            <tr>
                <td>North/South</td>
                <td>UK</td>
            </tr>
            <tr>
                <td>Paris specialites</td>
                <td>France</td>
            </tr>
        </table>
    </body>
    <script>
        // Function to filter the table, based on search
        function myFunction() {
            
            var input, filter, table, tr, td, i, txtValue;
            input = document.getElementById("myInput");
            filter = input.value.toUpperCase();
            table = document.getElementById("myTable");
            tr = table.getElementsByTagName("tr");
            for (i = 0; i < tr.length; i++) {
                td = tr[i].getElementsByTagName("td")[0];
                if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                }
                else{
                    tr[i].style.display = "none";
                }
                }       
            }
        }
        
        // Event Listener, to filter the table, based on search
        // var input = document.getElementById('myInput');
        // input.addEventListener('click', function(){
        //     var myTable = document.getElementById('myTable');
        //     var row = myTable.getElementsByTagName('tr');
        //     var value = input.value;
        //     var ex_val = value.toUpperCase();
        //     for(var i=1;i < row.length;i++){
        //         var content = row[i].getElementsByTagName('td')[0]; 
        //         var ex_con = content.textContent.toUpperCase();
        //         if ( ex_con.indexOf(ex_val) > -1){
        //             row[i].style.display = '';
        //         }
        //         else{
        //             row[i].style.display = 'none';
        //         }
        //     }
        // })
    </script>
</html>

Importing from packages sub directory

I am writing a package for npm, and I was wondering how I can setup the packages, so that people can import specifics thing from the package subdirectory.

For example, I have a package name “MyPackage” that has “myFunction” in the path lib/my/subdir.

import {myFunction} from “MyPackage” works.

I want to be able to also do this:

import { myFunction} from “MyPackage/my/subdir”

Right now, I have to write”

import {myFunction} from “MyPackage/lib/my/subdir”

The extra “lib” is due to the where npm build produce the production codes.

What is the most appropriate terminology/vocabulary when discussing React Hook’s useState? [closed]

I am teaching React in one of my courses, and I want to know what the most appropriate terminology is for React Hook’s useState. I have reviewed the documentation for React, and I don’t think they’re very clear about what to call specific constructs in the code.

const [state, setState] = useState(initialState);

What do you call state, setState, and useState? Here’s what I’ve come up with talking to my colleagues:

  • useState is the “Hook”. It tells React that you want to create a Stateful Value.
  • setState is the “Hook Setter”. It is certainly a Setter, although that is generic and vague. Internally, the React source code seems to refer to this as a “Dispatch” function. It can manipulate the Stateful Value.
  • state is the “Hook Accessor”. It is not a function, it is technically a constant (though a temporary one). It is not a value, since it is an identifier referencing a Stateful Value (in the same sense that a variable is not a value). Internally, they refer to this as “state”, but that seems quite generic.

What terminology does the community tend to use to differentiate the idea of the constant identifier holding the reference to the stateful value from the stateful value? Or is there some terminology that you individually use that can separate these ideas?

Restrict results for Google Places autocomplete to allow only addresses with building

I use Google Places Autocomplete to present list of predictions to the user while it’s typing.
My requirement is to allow users to pick only addresses that include building number (street_number in API terms).

The configuration I use is shown below:

let gac = new google.maps.places.Autocomplete(
                  (autocomplete), {
                    types: ['address'],
                    componentRestrictions: {'country': ["us"]},
                    fields: ['formatted_address', 'address_components']
                  }
                );

With this settings user can pick address that includes only Street name without building part specified.

I can add validation message if user picks address without building number (streen_number of an address_componenst arrey, but I would not like to show such results at all.

I studied the list of Types that I can use to restrict results, but didn’t find any better than “address”.

Can someone help to meet my requirements?

(NodeJS) Is there a way in a model to create an object or set it at false is nothing in true in mongoose

Hope you’re good.
I don’t know how to describe my problem, so I’ll try to be as clear and concise as possible.
If despite this the problem is not clear, do not hesitate to tell me so that I can reformulate it.

I have to try to create a model that differs depending on whether something is true or false, I explain :

compliance: {
    transactionsPending: {
      deletePending: boolean;
    };
  }; // OK 

Let’s say I have this in my model, I want to be able to make sure that if everything is false in this model, I have the following model:

compliance: false // OK 

Best regards,

How to highlight text when entering into input search bar

Search Bar Without Entry
Search Bar With Entry
In the images above, I have a search bar that allows for input, and filters once an input has been given. However, I want to go one step further and add a highlight to the text when an input has been made. In this example, for picture 2, I would want text highlighted for those selected. This is my current code below.

function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');

// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
  a = li[i].getElementsByTagName("a")[0];
  txtValue = a.textContent || a.innerText;
  if (txtValue.toUpperCase().indexOf(filter) > -1) {
    li[i].style.display = "";
    li[i].style.color = 'green';
  } else {
    li[i].style.display = "none";
  }
}

Return result from MongoClient.connect [duplicate]

i hope someone can help a JavaScript-Newbie. I am trying to retrieve data from a MongoDB and return the result in a function.

test() 
{
    var list = [];
    MongoClient.connect(url, (err, client) => {
        if (err) throw err;
        const db = client.db("test");
        db.listCollections().toArray().then((docs) => {
            list = docs;
        }).catch((err) => {
            console.log(err);
        }).finally(() => {
            client.close();
        });
    });
    return list;
}

When i call console.log(test()) the list is always empty. I know, thats because its an asynchronous function. But how can i solve the Problem?

Changing between themes with Javascript

I’m trying to make a dark/light theme toggle on my website. The SVG file switches back and forth on every click, but there’s an issue with the theme not switching every click.

First two clicks – theme changes as expected.

Third and fourth clicks – SVG image still changes each click, but theme doesn’t change

Fifth and sixth clicks onward – theme changes as expected, cycle repeats

HTML:

<div id="themes">
   <img id="current-theme">
</div>

CSS:

body{
  background-color: #ccc;
}

#themes {
  text-align: right;
  margin-right: 10em;
  margin-top: 2em;
  transform: scale(1.5);
  cursor: pointer;
}

.dark-mode {
  background-color: rgb(65, 65, 65);
  transition: background-color 0.5s ease;

  h1 {
    color: white;
  }

  h3 {
    color: white;
  }

  button {
    background-color: white;
    color: black;
  }
}

.light-mode {
  background-color: #ccc;
  transition: background-color 0.5s ease;

  h1 {
    color: var(--primary-color);
  }

  h3 {
    color: black;
  }

  button {
    background-color: black;
    color: white;
  }
}

Javascript:

//default theme is light
document.getElementById("current-theme").src = "images/moon.svg"

var currentTheme = document.getElementById("current-theme");
currentTheme.setAttribute("onClick", "toDarkTheme()");

var theme = document.body;

function toDarkTheme() {

  document.getElementById("current-theme").src = "images/sun.svg";
  theme.classList.toggle("dark-mode");
  //currentTheme.removeAttribute("onClick");
  currentTheme.setAttribute("onClick", "toLightTheme()");
}

function toLightTheme() {

  document.getElementById("current-theme").src = "images/moon.svg";
  theme.classList.toggle("light-mode");
  //currentTheme.removeAttribute("onClick");
  currentTheme.setAttribute("onClick", "toDarkTheme()");
}


I’ve included a link to the code in jsfiddle so you can see exactly what’s happening. Thank you for any help/advice you can give!

https://jsfiddle.net/6op0fx7L/2/#&togetherjs=zTrev7ILNd

Matching the saturation value of a HSL color

I am trying to match only the saturation value of a HSL color, for example given hsl(190, 40%, 50%) as an input, I would like to match the 40/40%. I have trying using lookarounds for this, but everything I tried just didn’t really work.

I have the following regex which matches pretty much any HSL color I would need: /hsla?(s*(-?(d{1,3}|d{1,3}.d+)(deg|%)?)s*(,s*|s+)(-?(d{1,3}|d{1,3}.d+)%?)s*(,s*|s+)((d{1,3}|d{1,3}.d+)%?)s*((,s*|s*/s*)(0|(0?.d+)|1))?s*)/gi. How would I go about only selecting the saturation value?

Storing the contents of an axios response into a variable in typescript [duplicate]

I’m relatively new to javascript and typescript in general and am struggling to understand the concept of async/await and Promises. (My knowledge is more Python based)

I am trying to make sense of why this function won’t work.

const getData = () => {
  var myData: string;

  axios.get(myEndPoint)
  .then((response) => {
    console.log(response.data) // this outputs the correct data
    myData = response.data
    return myData
  })
  .catch((error) => {
    return error
  });

And then outside this function I would like to get the contents of myData like so

const data_contents = getData()

However this would give me a value of undefined

I have tried various methods including changing the function getData() to an async function and declaring await for axios.get() however that would return a Promise {<pending>} instead and not the actual contents of response.data.

If someone could help explain what I’m doing wrong and point me in the right direction it would be really appreciated. Thanks a lot!