Why does React.createElement need to be called twice?

I am in the process of learning React and was stuck at once place. To make things clear, I am first trying to use React without any JSX. All I am loading is the React and React DOM library. I defined a component like this:

function Weekday(props) {
            return React.createElement('p', null, `Today is ${props.day}`);
        }

        let dayElem = React.createElement(Weekday, {day: 'Monday'});

        ReactDOM.createRoot(document.getElementById('app')).render(dayElem);

My question is why do I need to call createElement twice? The function Weekday is already returning a React element. So, what did I have to call createElement another time while passing it the function name Wednesday. Why couldn’t dayElem simply be like this:

let dayElem = Weekday({day: 'Monday'});

How to run Phaser.js files on code editor app?

I’ve been using Repl.it to work with Phaser, but I’m looking into offline app versions that might run faster. However, I’ve tried Atom, Brackets, and VS Code, and they all seem to be unable to debug the files the same way that Repl.it does. I’m getting error messages such as “unexpected reserved word” or “expected an identifier and instead saw ‘class'” that I wouldn’t normally see when I run my code on Repl.it, while the debugger doesn’t show the errors I actually want to see that are present. Is there something I’m doing wrong that is causing these problems?

Here’s an example set of files. Code Sandbox works as well, but it is also fully browser-based. Could you let me know how to run these files with an offline code editor app?

How do I wait to update an HTML header until promise is resolved?

I am building my first electron application and I am running into a JS error I am not sure how to fix.

I have managed to setup the IPC for a basic password manager application. The use-case is simple:

  1. I click an HTML button and the frontend connects to the backend and delivers a keyword from which to build a password.
  2. Password is generated.
  3. Upon completion, the password is returned to the frontend to be displayed via HTML.

Here is an example:
keyword = dog
generated password –> dog-jdls4ksls

The issue I am seeing is that instead of printing the generated password, I am seeing:
[object Object]-jdls4ksls

My best guess is that, since I am using async/await, I am printing the promise object instead of the returned value. I do not know, however, how I would block to wait for completion. Any help would be appreciated!

For context, I am primarily a backend developer, with plenty of python and C/C++/C# experience. My goal is to rebuild a C#/.NET GUI application into an electron app.

Here is all my code.

main.js

const {app, BrowserWindow, ipcMain} = require("electron")
const path = require("path")

function generatePassword(keyword) {
    console.log(keyword)
    return keyword + '-' + Math.random().toString(36).substring(2,12)
}

function createWindow () {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        resizable: false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })

    win.loadFile('html/passwordGen.html')
}

app.whenReady().then(() => {
    ipcMain.handle("generatePassword", generatePassword)
    // console.log(generatePassword('test string')) // works
    createWindow()
}).catch(error => {
    console.log(error) // log error to console
    app.quit() // quit the app
})

preload.js

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('main', {
    genPW: (keyword) => ipcRenderer.invoke("geåneratePassword", keyword)
})

render.js

async function testClick () {
    const pw_root = document.getElementById("keyword")
    const pw_label = document.querySelector("#password")
    pw_label.innerText = await window.main.genPW(pw_root.value)
}

passwordGen.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Password Generator</title>
    <link rel="stylesheet" href="../css/style.css">
    <script src="../render.js"></script>
</head>
<body>
    
    <h1>Password Generator</h1>
    <input type="text" id="keyword" placeholder="Please enter a keyword...">
    <button id="btn" onclick="testClick()">Generate Password</button>

    <h1 id="password"></h1>
</body>
</html>

d3.v5.min.js:2 Error: attribute d: Expected moveto path command (‘M’ or ‘m’), “function a(a){va…”

I am trying to plot a multi-line graph with d3.js but I am getting this error:

Error: attribute d: Expected moveto path command (‘M’ or ‘m’), “function t(t){va…”.

I have been stuck at it a while now and tried everything I could think of, to help you in your reflections, Find the code that I use below.

// set the dimensions and margins of the graph
var margin = {top: 10, right: 30, bottom: 30, left: 60},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;

const dateParser = d3.timeFormat("%Y-%m-%d %H:%M:%S");

data.forEach(function(d) {
    d.ts = dateParser(new Date(d.ts));
    d.value = parseFloat(d.value)
});


// append the svg object to the body of the page
var svg = d3.select("#graph")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
      "translate(" + margin.left + "," + margin.top + ")");

//Read the data

  // group the data: I want to draw one line per group
  var sumstat = d3.nest() // nest function allows to group the calculation per level of a factor
.key(function(d) { return d.key;})
.entries(data);

 // Add X axis --> it is a date format
  var x = d3.scaleLinear()
.domain(d3.extent(data, function(d) { return d.ts; }))
.range([ 0, width ]);
  svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(5));

 // Add Y axis
 var y = d3.scaleLinear()
.domain([0, d3.max(data, function(d) { return +d.value; })])
.range([ height, 0 ]);
 svg.append("g")
.call(d3.axisLeft(y));

// color palette
var res = sumstat.map(function(d){ return d.key }) // list of group names
var color = d3.scaleOrdinal()
.domain(res).range(['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#ffff33','#a65628','#f781bf','#999999'])

 // Draw the line
 svg.selectAll(".line")
  .data(sumstat)
  .enter()
  .append("path")
    .attr("fill", "none")
    .attr("stroke", function(d){ return color(d.key) })
    .attr("stroke-width", 1.5)
    .attr("d", function(d){
      return d3.line()
        .x(function(d) { return x(d.ts); })
        .y(function(d) { return y(d.value); })
    })

I cannot figure what I am doing wrong, in case the example I am looking at is this link. I am fairly new to d3 and it is not an easy library to use

Syntax error in JISON with simple grammar

I’m trying to implement a very simple parser, but I’m having a problem. I have the following grammar:

axioma : '{' list_instr '}' EOF;

list_instr : list_instr instr
           | instr;

instr     :  call_func;

call_func : 'call' ID '(' params_list ')'
          |  'call' ID '(' ')';

params_list : params_list ',' NUM
            | NUM;

The grammar contains more productions but it is this part that is creating conflicts. The problem comes when trying to parse the following text:

{
    call add(2, 3)
}

JISON tells me that there was a syntactic error in ‘(‘, however the characters are provided by the lexical analyzer, so I think the problem may be the grammar but I really don’t understand what the cause is. Any ideas?

Why can’t I redirect to my failure page using node.js?

I am working on my newsletter project using Mailchimp API, it works but I can’t redirect to a failure page if the status code is not 200, the browser says localhost refused to connect meanwhile success page redirection works great.
here’s my code:

app.post("/", async(req, res, next)=>{
  const {fName, lName, email} = req.body.user;
  const response = await mailchimp.lists.addListMember("List_ID", {
    email_address: email,
    status: "subscribed",
    merge_fields:{
      FNAME: fName,
      LNAME: lName,
    },
  });
  if(res.statusCode === 200){
    res.sendFile(__dirname + "/success.html");
  }
  else{
    res.sendFile(__dirname + "/failure.html");
  }

});

Speed test xmlhttprequest

Good afternoon. Please tell me how can I return the ‘event.
loaded’ which then dispatch it to the state

const startSpeedTestAsync = () => async (dispatch: Dispatch) => {
  const url = config.SPEED_TEST;


dispatch(setLoadTest(true));

const startTime = new Date().getTime();


dispatch(startSpeedTest({ startTime, isShowInfo: false }));



 const endRequest = (data: unknown) => {
    const endTime = new Date().getTime();
    dispatch(setEndTime(endTime));
    dispatch(calcSpeed(data));
    dispatch(stopSpeedTest({ isLoadTest: false, isShowInfo: true }));
  };



const sendHttpRequest = (metod: string, currenUrl: string) => {
    const promise: Promise<unknown> = new Promise((resolve) => {
      const xhr = new XMLHttpRequest();

  xhr.timeout = 5000;

  xhr.onprogress = function (event) {
    console.log('loaded: ', event.loaded);
    return event.loaded;
  };
  xhr.onreadystatechange = function () {
    // Only run if the request is complete
    if (xhr.readyState !== 4) return;
    resolve(xhr.onprogress);

    // resolve(xhr.onprogress);
  };
  xhr.open(metod, currenUrl);
  xhr.send();
});
return promise;

};

  sendHttpRequest('GET', url)
    .then((response: any) => console.log(response))
    .catch(endRequest);
};

I can not understand how to properly process the request that everything turned out. I’m trying to implement a request for xmlhttprequest
and return the size of the downloaded file to then calculate the speed of the Internet connection. The problem is that I don’t know how to return this size.

please i a am having an issue, i am trying to remove some div tags based on login role in php and javascript

it is working but once i reload the page it shows the div tag i removed in less than a sec, i should have used display:none but any user can go to inspect element and change the the display to block

here is my code

<?php
//if ($row['login_type'] == 'Advertiser'){
?>
        <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script>
     $(document).ready(function() {
     $(window).on("load", function() {
    
    $("#Div1").remove();
    $("#Div2").remove();
    $("#Div3").remove();
  }) 
 });
</script>
<?php }?>

How to prevent content(Tasks) to disappear after REFRESHING

I am trying to make a simple To-Do like application. I want the “Tasks” which I add to remain even after closing the window or at least after refreshing. I tried to achieve that using MongoDB but I couldn’t.
I think a simpler way to achieve this is by using arrays but I am not able to understand how to do that.
Please suggest me some way to achieve the above results….

let div = document.getElementById('tasks');
let add = document.getElementById('add');
let newTask = document.getElementById('newTask');

let c = 0;

add.addEventListener("click", function () {
    let newt = newTask.value;
    newTask.value = null;
    let cbox = document.createElement("input");
    let br = document.createElement("br");
    cbox.type = "checkbox";
    cbox.id = "check";
    let d = document.createElement("div");
    div.append(d);
    d.id = "nd";
    d.append(cbox);
    d.append(newt);
    c += 1;
    if (c === 12) {
        add.disabled = true;
        newTask.value = "Stack Overflow";
    }
});
/* body {
    background-color: #42f5f5
} */

.card {
    margin: 0 auto;
    float: none;
    /* margin-bottom: 10px; */
    /* border: none; */
    /* background-color: rgb(248, 179, 88); */
}

.container {
    margin-top: 2.5rem;
}

#title {
    width: 200px;
    border: none;
    font-size: larger;
    font-weight: bold;
}

#newTask {
    width: 200px;
}

#add {
    margin-top: 1rem;
}

#newTask {
    margin-top: 1rem;
}

#plus {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 15px;
}

#nd {
    font-size: 20px;
    margin-top: 5px;
    margin-bottom: 10px;
}

#check {
    margin-left: 20px;
    height: 15px;
    width: 15px;
    margin-right: 10px;
}
<!doctype html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
            integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <link href="ToDo.css" rel="stylesheet">
        <title>To-Do</title>
    </head>

    <body>

        <div class="container">
            <div class="card" style="width: 35rem;height: 42rem;">
                <div class="card-body">
                    <p style="font-size: 2rem;font-weight: bold;">
                        <input type="text" class="form-control" id="title" placeholder="Title">
                    </p>
                    <p id="main">
                    <div id="tasks">

                    </div>
                    <form class="form-inline">
                        <div class="form-group mx-sm-3 mb-2">
                            <input type="text" class="form-control" id="newTask" autocomplete="off"
                                placeholder="Enter new task">
                        </div>
                        <button type="button" class="btn btn-primary mb-2" id="add">Add Task</button>
                    </form>
                    </p>
                </div>
            </div>
        </div>

        <script src="ToDo.js"></script>
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
            crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>
    </body>

</html>

How do I close a prompt upon clicking cancel in JS?

I cannot for the life of me figure out how to close the prompt altogether upon pressing cancel in my code for a guessing game. I’ve tried several things, but each time either the code ignores what I’m trying to do, or ends in an error. Here’s the code in question:

let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);

let numTries = 1

console.log(numGuess);

numGuess = parseInt(numGuess)

if (prompt == null) {

alert (`Press F5 to play again.`) 


}
if (numGuess === num) {

  alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);

}

else while ((numGuess !== num) && (numTries <3))

{

  numTries = numTries++

  alert (`Incorrect guess. Try again.`)

}

length property in built-in Object, Number

Why does the built-in Object, Number, have a length property?

var n = Number;
n;
EPSILON: 2.220446049250313e-16
MAX_SAFE_INTEGER: 9007199254740991
MAX_VALUE: 1.7976931348623157e+308
MIN_SAFE_INTEGER: -9007199254740991
MIN_VALUE: 5e-324
NEGATIVE_INFINITY: -Infinity
NaN: NaN
POSITIVE_INFINITY: Infinity
isFinite: ƒ isFinite()
isInteger: ƒ isInteger()
isNaN: ƒ isNaN()
isSafeInteger: ƒ isSafeInteger()
length: 1 // For what??

Error: Cannot POST /includes/signup.inc.php

I’m using Node.js to help build a web app and am trying to create a login form + signup form but when submitting the form i get the following error: Cannot POST /includes/signup.inc.php . I’m new to php and MySQLi and thus are following this tutorial: https://youtu.be/gCo6JqGMi30 and have a db running with phpmyadmin (not too sure whether it could be an issue with accessing that as i never came accross an option to set usernames or passwords for the db). The issue might also be to do with the routing on routes.js. Here’s my code for the affected areas:
dbh.inc.php:

<?php

$serverName="localhost";
$dBUsername="root";
$dBPassword="";
$dBName="revisionflashcards";

$conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

signup.inc.php:

<?php

if (isset($_POST["submit"])) {
    echo "It works!";
}
else {
    header("location: ../views/index.ejs");
}

createacc.php:

<!DOCTYPE html>
<head>
    <script src="https://kit.fontawesome.com/855632da8a.js" crossorigin="anonymous"></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=Poppins&display=swap" rel="stylesheet">
</head>
<style>
    .center {
      margin: auto;
      width: 50%;
      padding: 10px;
    }
    .button {
      border: none;
      color: white;
      padding: 10px 40px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      margin: 4px 2px;
      transition-duration: 0.4s;
      cursor: pointer;
    }
    
    .button1 {
      background-color: white;
      color: black;
      border: 2px solid #4da9ff;
    }
    
    .button1:hover {
      border-radius: 10px;  
      background-color: #4da9ff;
      color: white;
    }

</style>
<section class="signup-form">
    <h1>Create Account</h1>
    <form action="../../includes/signup.inc.php" method="post" style="margin: auto; width: 250px;">
        <i class="fa-solid fa-user"></i><input type="text" name="uid" size="25" placeholder="Create A Username"/><br>
        <i class="fa-solid fa-lock"></i><input type="password" name="pwd" size="25" placeholder="Create A Password"/><br>
        <i class="fa-solid fa-lock"></i><input type="password" name="pwdrepeat" size="25" placeholder="Repeat Password"/><br>
        <i class="fa-solid fa-envelope"></i><input type="text" name="email" size="25" placeholder="Your Email"/><br>
        <i class="fa-solid fa-tag"></i><input type="text" name="name" size="25" placeholder="Full Name"/><br>
        <button class="button button1" type="submit" name="submit">Sign Up</button>
    </form>
</section>

routes.js:

var express = require("express");

var router = express.Router();


router.get("/", function(req, res){
    console.log("A1 Cabs!? A1 Cabs!? Testing Testing 123!")
    res.render("index");
});


router.get("/cards", function(req, res){
    res.render("cards");
});

router.get("/login", function(req, res){
    res.render("acc/login");
});

router.get("/createacc", function(req, res){
    res.render("acc/createacc");
});

router.get("/projectpage", function(req, res){
    res.render("projecthub");
});

module.exports = router;

Thank you any help would be appreciated. 🙂

Increase qty by 1 if item already exist in cart – Reactjs/NextJS

I have found many questions similar to the subject, however, I couldn’t understand the logic, as most of these are asked/explained in the PHP/ MySQL community.

I’m building an eCommerce store, where I need to handle cart items. The problem is already mentioned in the subject. Below is a short snippet of my code.

const [cartItems, setCartItems] = useState([]) // initial state of cartItems array
const handleCartUpdate = (id,title, price, qty) => {
  // first checking if  cart is empty or not
  const cartLength = cartItems.legnth >=1 ? true : false
  // Check if item exist with the id as given in parameters
  if(cartLength) {
    const checkItemExist = cartItems.find(item => item.id == id)
    // Now, if item exist, update the propert 'qty' , My approach is as under:
    if (checkItemExist) {
      cartItems.map(product => {
        if(product.id == id) {
          return {product, qty: qty+1
        }
      }
      return product
      setCartItems(...cartItems, product)
    }
  } else {
    setCartItems(...cartItems, {...})
  }
}

After that, I am unable to understand how to update the cartItems