Table inside map is not rendering [duplicate]

I’m iterating into a JSON file using map twice, but when I try to render the returned value of the second one, I got nothing. By console, the value is shown properly.

const Container2 = (props) => {

  const data = Array.from(props.data);

  return(
    <div>
      <table>
        <thead>
          <tr>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {data.map(item => {
            item.metadata.map(item2 => {
              return(
                <tr key={data.id}>
                  <td>{item2.metadata.name}</td> //here I got nothing
                </tr>
              )
            })
          })}
        </tbody>
      </table>
    </div>
  )
}

Why am I getting nothing when rendering the returned value of the second map?

How can I store a boolean value for every user to see live? [closed]

I want to make a little website game where a user can click either yes or no, the catch being that the decision is stored on the website for everyone to see the idea being that people can fight over the decision. (My plan is that once you vote you have to wait 30 seconds to vote again)

My idea was to have this live update using a function that refreshes the page every 30 seconds so I’m not too concerned about live updating.

The issue is I’m not sure how to store the data on the site so that everyone has the same data?

It’s just a fun game so if there’s a delay for some users that’s fine.

Can I achieve this with js?

I’m planning on building this in Webfliow ideally but not required

FIREBASE WARNING: Exception was thrown by user callback. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

I’m doing an application in NodeJs with back-end using express and front-end. The back-end uses firebase-admin for consult and edit data in realtime-database.

During my Development, I’ve noticed that clicking twice in buttons that sends HTTP must be carefully handled to prevent multiple calls to the back-end.

The problem is that I have a form that adds data in firebase that calls this function in the back-end:

app.get('/set-client', (req, res) => {
  let user = sessions_map.get(req.sessionID)
  let uid_client = req.query.client_uid;
  let database_client = req.query.database;
  
  const ref = db.ref(`users/${user.uid}`)
  
  ref.update({ 'client': uid_client}).then(function(){
    console.log("Data saved successfully.");
    res.status(200).send("successful")
  }).catch(function(error) {
    console.log("Data could not be saved." + error);
    res.status(201).send("failed")
  });
});

//****Button function in Front-End ******\

var xhr = new XMLHttpRequest();
xhr.withCredentials = true
xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        if(this.responseText == "error"){
            return
        }
        window.location.href = "../home.html";
    }
    else if(this.readyState == 4 && this.status == 0){
        alert("Connection Failed");
        window.location.href = "../index.html";
    }
};
xhr.open('GET', back_end+`/set-client?client_uid=${uid_client}&database=${database}`);
xhr.send()

When I click the button twice, I receive this error:

[2022-05-31T20:34:37.262Z]  @firebase/database: FIREBASE WARNING: Exception was thrown by user callback. Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesexpresslibresponse.js:794:10)
    at ServerResponse.json (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesexpresslibresponse.js:275:10)
    at ServerResponse.send (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesexpresslibresponse.js:162:21)
    at C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endstart.js:235:11
    at valueCallback (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:18153:22)
    at CallbackContext.onValue (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:15789:31)
    at C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:16645:46
    at exceptionGuard (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:4018:9)
C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:4029
            throw e;
            ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesexpresslibresponse.js:794:10)
    at ServerResponse.json (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesexpresslibresponse.js:275:10)
    at ServerResponse.send (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesexpresslibresponse.js:162:21)
    at C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endstart.js:235:11
    at valueCallback (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:18153:22)
    at CallbackContext.onValue (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:15789:31)
    at C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:16645:46
    at exceptionGuard (C:UsersjulioOneDriveÁrea de Trabalhosistemas-simcsimc40-back-endnode_modulesfirebase-adminnode_modules@firebasedatabase-compatdistindex.standalone.js:4018:9) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

I know firebase makes asynchronous calls, and I think that while the firebase is still saving the data in database, the second http request calls and it messes the processes.

The only way I could solve this was in the front-end, adding a timer at the button of 3s so, it couldn’t send 2 requests. But this approach might fail if the request takes more than 3s that is why I’m still worried about it.

I’d like to know how to solve this in back-end side.

Thank you guys!

How can I check if a user already exist in mongoDB?

I am creating an account creation system with express.js but I would like to know how I can know if the user already has an account (with his email) on my DB in order not to register him twice.

const router = require("express").Router(),
    User = require("../database/models/User.model.js");

const cryptoJS = require("crypto-js");

//REGISTER
router.post("/register", async (req, res) => {
    const { username, email, password } = req.body;

    if (User.findOne({ email: email })) {
        return res.status(400).json({
            message: "This email is alredy existing in our database" 
       });
    } else {
        const user = new User({
            username: username,
            email: email,
            password: cryptoJS.AES.encrypt(
                password,
                process.env.CRYPTO_KEY
            )
        });
        await user.save()
            .catch(err => res.status(500).json({ error: err.message }));
    }
});

module.exports = router;

Can I protect custom events from “preventDefault”?

We have a Stencil web component that renders a user dialog. It consists of an “outerComponent” and an “innerComponent”.
The outer one cares about dealing with the browser (props, load stuff from cookies etc.) and the inner one renders the actual HTML and lets the user operate it.

(Actually there are more components used inside, from a different project for the UI components such as checkbox, button etc. But I don’t think that’s relevant here.)

When a checkbox, button etc. is clicked in <inner-component> an onclick-handler within the component is called that executes some UI logic (e.g. set the “checked” property) and then emits a custom event, e.g.:

@Event() checkboxToggleModalEvent: EventEmitter<OptionType>;
...

<checkbox-comp fid="...">
  <input type="checkbox" checked={optionCheckbox.userSelection} onClick={this.handleCheckbox} />
  ...
</checkbox-comp>
...

private handleCheckbox(event: Event) {
    const checkboxElement: HTMLInputElement = event.target as HTMLInputElement;
    ...
    const selection: OptionType = { name: indexId, userSelection };

    this.checkboxToggleModalEvent.emit(selection);
}

Now, in <outer-component> this event is listened for and the handler cares for the “technical” logic:

    @Listen("checkboxToggleModalEvent")
    checkboxToggleModalEventHandler(event) {
        LogService.log.debug(event);

        ... some technical logic
    }

This works fine in most cases. Now we have an integration on one site, where the events apparently do not get emitted correctly or somehow lost in the middle.
The UI logic is executed normally but the handler in outerComponent never gets called.

I was able to find the piece of code from an integrated library that causes the problem (sorry for pasting the whole function!):

// From the imported library on customer website:
function(t, exports) {
    try {
        var e = new window.CustomEvent("test");
        if (e.preventDefault(),
        !0 !== e.defaultPrevented)
            throw new Error("Could not prevent default")
    } catch (t) {
        var n = function(t, e) {
            var n, r;
            return e = e || {
                bubbles: !1,
                cancelable: !1,
                detail: void 0
            },
            n = document.createEvent("CustomEvent"),
            n.initCustomEvent(t, e.bubbles, e.cancelable, e.detail),
            r = n.preventDefault,
            n.preventDefault = function() {
                r.call(this);
                try {
                    Object.defineProperty(this, "defaultPrevented", {
                        get: function() {
                            return !0
                        }
                    })
                } catch (t) {
                    this.defaultPrevented = !0
                }
            }
            ,
            n
        };
        n.prototype = window.Event.prototype,
        window.CustomEvent = n
    }
}

If I remove this, everything works as expected.

Now, I’m wondering if we can somehow “protect” our events from being intercepted like this as the component should really work in any case (that’s why we chose this technology).

But I also would be very grateful for any hints to what might actually cause the problem.

Thanks a lot!!

Problem with FormData in ReactJS (empty object)

I have one problem with formdata when i use reactjs, i think is all ok but when i console.log the formdata, the result is an empty object and the body of request same
(backend express)
and in the fetch request the body is wrapped by JSON.stringify()

The code in question is:

REACT Code

import React, { useState, useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { login, reset } from "../shared/reducers/auth/auth-reducer";
import { toast } from "react-toastify";
import { VALIDATOR_REQUIRE } from "../shared/util/validators";
import Spinner from "../shared/components/UI/LoadingSpinner";
import Input from "../shared/components/UI/Input";
import "./Login.css";
import "./shared-form.css";
import Button from "../shared/components/UI/Button";
import { useForm } from "../shared/reducers/form/form-reducer";

const Login = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const [formState, inputHandler] = useForm(
    {
      email: {
        value: "",
        isValid: false,
      },
      password: {
        value: "",
        isValid: false,
      },
    },
    false
  );
  console.log(formState.inputs.email.value);

  const { user, isLoading, isError, isSuccess, message } = useSelector(
    (state) => state.auth
  );
  console.log(user);

  useEffect(() => {
    if (isError) {
      toast.error(message);
    }

    if (isSuccess) {
      navigate("/");
      toast.success(message);
    }

    dispatch(reset());
  }, [user, isError, isSuccess, message, navigate, dispatch]);

  const onSubmit = (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append("email", formState.inputs.email.value);
    formData.append("password", formState.inputs.password.value);

    console.log(formData())
    dispatch(login(formData));
  };

  return (
    <>
      {isLoading && <Spinner />}
      <div className="form__container form__container__login">
        <section className="heading heading-login">
          <h1>Login</h1>
          {isError && <p className="error-message">{message}</p>}
        </section>

        <section className="form form-login">
          <form onSubmit={onSubmit}>
            <Input
              id="email"
              onInput={inputHandler}
              label="Email"
              validators={[VALIDATOR_REQUIRE()]}
            />
            <Input
              id="password"
              onInput={inputHandler}
              label="Password"
              validators={[VALIDATOR_REQUIRE()]}
            />
            <Button type="submit">Submit</Button>
          </form>
        </section>
      </div>
    </>
  );
};

export default Login;

(i think value of inputs all are ok but formdata still is empty)
What is the problem?

Data not put into Paragraph JS/AJAX/PHP

My php script echoes

Connection successful{"name":"James","dateOfBirth":"2002-10-10","companyname":"Apple"}

using

echo json_encode(array('name'=>$row['Name'], 'dateOfBirth'=>$row['dateOfBirth'], 'companyname'=>$row['companyname']));

In Javascript the different values should then be displayed in a Label, but the Labels return undefined

$(function() {

    $.ajax({
     type: "post",
     url: 'url',
     data: {usermail: 42},
     success: function(response){

         nameLabel.innerHTML = response.name;
         dateLabel.innerHTML = response.dateOfBirth;
         companyLabel.innerHTML = response.companyname;
         console.log(response);

     }
 });

});

(Odin Project Rock paper scissors) How do I make results appear only once and not show up each time you play a round?

So everytime you press on a button, a round of rps play and displays computer and player points. But instead of points just adding, they add and appear again below, I tried moving brackets on the eventListener so that it doesn’t include append results every time you press a button, but then I get playerSelection is not defined.

    let choice = ["rock","paper","scissors"];
    let random = choice[Math.floor(Math.random() * choice.length)];
    return random;
}

let computerPoints = 0;
let playerPoints = 0;

function playRound(playerSelection, computerSelection) {
    if (playerSelection === computerSelection) {
      return ("It's a draw!");
    } else if ((playerSelection === "rock") && (computerSelection === "scissors")) {
        ++playerPoints
      return ("You win! Rock beats scissors");
    } else if (playerSelection === "rock" && computerSelection === "paper") {
        ++computerPoints
      return ("You lose! Paper beats rock");
    } else if (playerSelection === "paper" && computerSelection === "rock") {
        ++playerPoints
      return ("You win! Paper beats rock");
    } else if (playerSelection === "paper" && computerSelection === "scissors") {
        ++computerPoints
      return ("You lose! Scissors beat paper");
    } else if (playerSelection === "scissors" && computerSelection === "paper") {
        ++playerPoints
      return ("You win! Scissors beat paper");
    } else if (playerSelection === "scissors" && computerSelection === "rock") {
        ++computerPoints
      return ("You lose! Rock beats scissors");
    }

}

//Play an exact amount of rounds logic

function game() {
      //Create new div for results
        const container = document.querySelector('.container');
        const results = document.createElement('div');
        container.appendChild(results)

      //Make clicking buttons react to functions

        const buttons = document.querySelectorAll('button');
        buttons.forEach((button) => {
        button.addEventListener('click', () => {
        playerSelection = button.className;

      //Make a player result appear
        
      const playerpp = document.createElement('p');
      playerpp.style.color = 'blue';
      playerpp.textContent = 'Player points: ' + playerPoints;
      container.appendChild(playerpp);

      //Make a computer result appear

        const computerpp = document.createElement('p');
        computerpp.style.color = 'red';
        computerpp.textContent = 'Computer points: ' + computerPoints;
        container.appendChild(computerpp);
      
      //Make computer's choice appear
        let computerSelection = computerPlay();
        const computerChoice = document.createElement('p');
        computerChoice.textContent = "Computer plays: " + computerSelection; 
        container.appendChild(computerChoice);

      //Make the actual battle appear

        const battle = document.createElement('p');
        battle.textContent = '' + playRound(playerSelection, computerSelection);
        container.appendChild(battle);

        if (computerPoints == 5) {
            alert("You lose!");
        } else if (playerPoints == 5) {
            alert("You win!");
        } 

  })
})
}



//console.log(("First to 3 wins!"));
game();

Youtube API loop stops

I’m very new to programming.
I’m trying to make a project where a locally hosted website, would fetch titles of the songs from a youtube playlist and then adds them to a list.
So far, it fetches the first 50 items/titles, but then the loop stops.
What goes wrong here?

let tracks = [];
let token = "";
let items;
let items_total;

function execute() {
        do {
        return gapi.client.youtube.playlistItems.list({
            "part": ["snippet"],
            "maxResults": 50,
            "pageToken": token,
            "playlistId": "id of the playlist"
        }).then(function(response) {
            let playlist = response;

            items = playlist.result.pageInfo.resultsPerPage;
            items_total = playlist.result.pageInfo.totalResults;
            token = playlist.result.nextPageToken;

            for (let i = 0; i < items; i++) {tracks.push(playlist.result.items[i].snippet.title)}
        },
        function(err) { console.error("Execute error", err); });
    } while (tracks.length < items_total)
}

How do I add render pagination with ellipsis conditionally in React

I have looked everywhere, watched videos and still couldn’t get the logic behind adding ellipsis in pagination.

I have created this component Pagination (please note this is just a sample component to demonstrate my question)

export const Pagination (props) {
const {maxPages, pageNumber} = props

const totalPageNumbers = []

for(let i = 1; i<= maxPages; i++){
totalPageNumbers.push(i)
} 

return (
<div>
<button disabled={pageNumber === 1}>prev</button>

{
totalPageNumbers.map(item, i) => (
<button onClick={() => someFunction()}> {item} </button>)
}
<button disabled={pageNumber === maxPages}>prev</button>
</div>

)}
  • totalPageNumbers is an array of the total pages
  • maxPages is a string of the total number
  • pageNumber is the current page

I would like to show something like this if total pages are 5 or more
1, 2, 3, 4, …, 5

if less than 5, it should be
1, 2, 3, 4

Right now everything works fine, but all pages are listed due to the map method above, so if I have 100, it will list 100. I would like to limit that number so it’s cleaner.
ellipsis no need to be clickable as long as they look like the example above, I will be super happy. Thanks a lot in advance!

Please help me with this logic, I have been stuck at this for the last 5 hours 🙁

What is causing this 2D fluid simulation to hang?

I attempted to build a fluid simulator based off the architecture of Jos Stam’s book, The Art of Fluid Animation, only I’m using node.js and canvas-sketch. I think I can finagle it to work, it’s just that when I run it as shown below, it hangs. No errors, but it only logs one bout of ‘Rolling’, the output in the animation loop. I think there may be something funny with my array declarations, I’ve tried spacing them out to different lines just in case it was making copies of itself instead of unique arrays, but no change. I was getting errors before I called the new Array functions in the sketch function.

Size doesn’t seem to be the problem, since it still hangs when NUM is super low. The paper passes a lot of references, I thought I could get around it by using globally defined variables and using a lot of void functions to change their values. Is this a flawed approach? Any suggestions?

const canvasSketch = require('canvas-sketch');

const NUM=1078;
const SIZE=(NUM+2)*(NUM+2);
const DT = 0.1, DIFF = 0.0, VIS = 0.0;

let U, V, uPREV, vPREV;
let DENS, dPREV;

//Call these macros, okay?
function IX(i, j) {return (i + (NUM + 2) * j);}
function SWAP(x0,x) {let tmp = x0; x0 = x; x = tmp;}

const settings = {
  dimensions: [NUM+2, NUM+2],
  animate:true
};

const animate=()=>{
  requestAnimationFrame(animate)
}

const sketch = () => {
  U = new Array(SIZE);
  V = new Array(SIZE);
  uPREV = new Array(SIZE);
  vPREV = new Array(SIZE);
  DENS = new Array(SIZE);
  dPREV = new Array(SIZE);

  console.log('Init');

  return ({ context, width, height }) => {
    console.log('Rolling'); //only logged once
    context.fillStyle = 'white';
    context.fillRect(0, 0, width, height);

    velStep(NUM, U, V, uPREV, vPREV, VIS, DT);
    densStep(NUM, DENS, dPREV, U, V, DIFF, DT);

    drawDens(context);
    drawVel(context);
  };
};

canvasSketch(sketch, settings);

function addSource(N, x, s, dt){
  for (let i=0; i<SIZE; i++){
    x[i] += dt * s[i];
  }
}

function setBound(N, b, x){
  for (let i=1; i<=N; i++){
    x[IX(0, i)]=b===1 ? -x[IX(1, i)] : x[IX(1, i)];
    x[IX(N+1, i)]=b===1 ? -x[IX(N, i)] : x[IX(N, i)];
    x[IX(i, 0)]=b===2 ? -x[IX(i, 1)] : x[IX(i, 1)];
    x[IX(i, N+1)]=b===2 ? -x[IX(i, N)] : x[IX(i, N)];
  }
  x[IX(0,0)] = 0.5 * (x[IX(1,0)] + x[IX(0 ,1)]);
  x[IX(0,N+1)] = 0.5 * (x[IX(1,N+1)] + x[IX(0 ,N)]);
  x[IX(N+1,0)] = 0.5 * (x[IX(N,0)] + x[IX(N+1 ,1)]);
  x[IX(N+1,N+1)] = 0.5 * (x[IX(N,N+1)] + x[IX(N+1 ,N)]);
}

function linSolve(N, b, x, x0, a, c){
  for (let n= 0; n< 20; n++){
    for (let j=1; j<=N; j++){
      for (let i=1;i<=N; i++){
        x[IX(i, j)] = (x0[IX(i, j)] + a * (x[IX(i-1, j)] + x[IX(i + 1, j)] + x[IX(i,j - 1)] + x[IX(i,j + 1)])) / c;
      }
    }
    setBound(N,b,x);
  }
}

function diffuse(N, b, x, x0, diff, dt){
  let a = dt * diff * N * N;
  linSolve(N, b, x, x0, a, 1 + 4 * a);
}

function advect(N, b, d, d0, u, v, dt){
  let i0, j0, i1, j1;
  let x, y, s0, t0, s1, t1, dt0;
  dt0 = dt*N;
  for (let j=1; j<=N; j++) {
    for (let i = 1; i <= N; i++) {
      x = i - dt0 * u[IX(i,j)];
      y = j - dt0 * v[IX(i,j)];

      if (x<0.5){x=0.5;}
      if (x>N+0.5){x=N+0.5;}
      i0=x; i1 = i0 + 1;

      if (y<0.5){y=0.5;}
      if (y>N+0.5){y=N+0.5;}
      j0=x; j1 = j0 + 1;

      s1 = x - i0;
      s0 = 1 - s1;
      t1 = y - j0;
      t0 = 1 - t1;

      d[IX(i, j)] = s0 * (t0 * d0[IX(i0, j0)] + t1 * d0[IX(i0, j1)]) + s1 * (t0 * d0[IX(i1, j0)] + t1 * d0[IX(i1, j1)]);
    }
  }
  setBound(N ,b, d);
}

function project(N, u, v, p, div){
  for (let j=1; j<=N; j++) {
    for (let i = 1; i <= N; i++) {
      div[IX(i, j)] = - 0.5 * (u[IX(i + 1, j)] - u[IX(i - 1, j)] + v[IX(i, j + 1)] - v[IX(i, j - 1)]) / N;
      p[IX(i, j)] = 0;
    }
  }
  setBound(N, 0, div);
  setBound(N, 0, p);

  linSolve(N, 0, p, div, 1, 4);

  for (let j=1; j<=N; j++) {
    for (let i = 1; i <= N; i++) {
      u[IX(i, j)] -= 0.5 * N * (p[IX(i + 1, j)] - p[IX(i - 1, j)]);
      v[IX(i, j)] -= 0.5 * N * (p[IX(i, j + 1)] - p[IX(i, j - 1)]);
    }
  }
  setBound(N, 1, u);
  setBound(N, 2, v);
}

function densStep(N, x, x0, u, v, diff, dt){
  addSource(N, x, x0, dt);
  SWAP (x0, x);
  diffuse (N, 0, x, x0, diff, dt);
  SWAP (x0, x);
  advect (N, 0, x, x0, u, v, dt);
}

function velStep(N, u, v, u0, v0, vis, dt){
  addSource(N, u, u0, dt);
  addSource(N, v, v0, dt);

  SWAP (u0, u);
  diffuse(N, 1, u, u0, vis, dt);
  SWAP (v0, v);
  diffuse(N, 2, v, v0, vis, dt);

  project(N, u, v, u0, v0);
  SWAP (u0, u);
  SWAP (v0, v);

  advect(N, 1, u, u0, u0, v0, dt);
  advect(N, 2, v, v0, u0, v0, dt);

  project(N, u, v, u0, v0);
}

function drawVel(context){
  let x,y,h;
  h = 1.0/NUM;

  context.save();
  for (let i=1; i<=NUM; i++){
    x = (i - 0.5) * h;
    for (let j=1; j<=NUM; i++){
      y = (j - 0.5) * h;

      context.beginPath();
      context.moveTo(x,y);
      context.lineTo(x + U[IX(i, j)], y + V[IX(i, j)]);
      context.strokeStyle='black';
      context.stroke();
    }
  }

  context.restore();
}

function drawDens(context){
  let x, y, h, d00, d01, d10, d11;

  h =1.0/NUM;

  context.save();
  for (let i=1; i<=NUM; i++) {
    x = (i - 0.5) * h;
    for (let j = 1; j <= NUM; i++) {
      y = (j - 0.5) * h;

      d00 = DENS[IX(i, j)];
      d01 = DENS[IX(i, j + 1)];
      d10 = DENS[IX(i + 1, j)];
      d11 = DENS[IX(i + 1, j + 1)];

      context.beginPath();
      context.fillStyle = 'blue';
      context.arc(x, y, d00, 0, Math.PI * 2);
      context.arc(x + h, y, d01, 0, Math.PI * 2);
      context.arc(x + h, y + h, d10, 0, Math.PI * 2);
      context.arc(x, y + h, d11, 0, Math.PI * 2);
      context.fill();
    }
  }
  context.restore();
}

Code directly from the book (meant for c):

#define IX(i,j) ((i)+(N+2)*(j))
#define SWAP(x0,x) {float * tmp=x0;x0=x;x=tmp;}
#define FOR_EACH_CELL for ( j=1 ; j<=N ; j++ ) {
for ( i=1 ; i<=N ; i++ ) {
#define END_FOR }}
void add_source(int N, float *x, float *s, float dt)
{
int i, size=(N+2)*(N+2);
for ( i=0 ; i<size ; i++ ) x[i] += dt*s[i];
}
void set_bnd(int N, int b, float *x)
{
int i;
for ( i=1 ; i<=N ; i++ ) {
x[IX(0 ,i)] = b==1 ? -x[IX(1,i)] : x[IX(1,i)];
x[IX(N+1,i)] = b==1 ? -x[IX(N,i)] : x[IX(N,i)];
x[IX(i,0 )] = b==2 ? -x[IX(i,1)] : x[IX(i,1)];
x[IX(i,N+1)] = b==2 ? -x[IX(i,N)] : x[IX(i,N)];
}
x[IX(0 ,0 )] = 0.5f*(x[IX(1,0 )]+x[IX(0 ,1)]);
x[IX(0 ,N+1)] = 0.5f*(x[IX(1,N+1)]+x[IX(0 ,N)]);
x[IX(N+1,0 )] = 0.5f*(x[IX(N,0 )]+x[IX(N+1,1)]);
x[IX(N+1,N+1)] = 0.5f*(x[IX(N,N+1)]+x[IX(N+1,N)]);
}
void lin_solve(int N, int b, float *x, float *x0,
float a, float c)
{
int i, j, n;
for ( n=0 ; n<20 ; n++ ) {
FOR_EACH_CELL
x[IX(i,j)] = (x0[IX(i,j)]+a*(x[IX(i-1,j)]+
x[IX(i+1,j)]+x[IX(i,j-1)]+x[IX(i,j+1)]))/c;
END_FOR
set_bnd ( N, b, x );
}
}
void diffuse(int N, int b, float *x, float *x0,
float diff, float dt)
{
float a=dt*diff*N*N;
lin_solve ( N, b, x, x0, a, 1+4*a );
}
void advect(int N, int b, float *d, float *d0, float *u,
float *v, float dt)
{
int i, j, i0, j0, i1, j1;
float x, y, s0, t0, s1, t1, dt0;
dt0 = dt*N;
FOR_EACH_CELL
x = i-dt0*u[IX(i,j)]; y = j-dt0*v[IX(i,j)];
if (x<0.5f) x=0.5f; if (x>N+0.5f) x=N+0.5f; i0=(int)
x; i1=i0+1;
if (y<0.5f) y=0.5f; if (y>N+0.5f) y=N+0.5f; j0=(int)
y; j1=j0+1;
s1 = x-i0; s0 = 1-s1; t1 = y-j0; t0 = 1-t1;
d[IX(i,j)] = s0*(t0*d0[IX(i0,j0)]+t1*d0[IX(i0,j1)])+
s1*(t0*d0[IX(i1,j0)]+t1*d0[IX(i1,j1)]);
END_FOR
set_bnd ( N, b, d );
}
void project(int N, float * u, float * v, float * p,
float * div)
{
int i, j;
FOR_EACH_CELL
div[IX(i,j)] = -0.5f*(u[IX(i+1,j)]-u[IX(i-1,j)]+
v[IX(i,j+1)]-v[IX(i,j-1)])/N;
p[IX(i,j)] = 0;
END_FOR
set_bnd ( N, 0, div ); set_bnd ( N, 0, p );
lin_solve ( N, 0, p, div, 1, 4 );
FOR_EACH_CELL
u[IX(i,j)] -= 0.5f*N*(p[IX(i+1,j)]-p[IX(i-1,j)]);
v[IX(i,j)] -= 0.5f*N*(p[IX(i,j+1)]-p[IX(i,j-1)]);
END_FOR
set_bnd ( N, 1, u ); set_bnd ( N, 2, v );
}
void dens_step(int N, float *x, float *x0, float *u,
float *v, float diff, float dt)
{
add_source ( N, x, x0, dt );
SWAP ( x0, x ); diffuse ( N, 0, x, x0, diff, dt );
SWAP ( x0, x ); advect ( N, 0, x, x0, u, v, dt );
}
void vel_step(int N, float *u, float *v, float *u0, float
*v0, float visc, float dt)
{
add_source ( N, u, u0, dt ); add_source ( N, v,
v0, dt );
SWAP ( u0, u ); diffuse ( N, 1, u, u0, visc, dt );
SWAP ( v0, v ); diffuse ( N, 2, v, v0, visc, dt );
project ( N, u, v, u0, v0 );
SWAP ( u0, u ); SWAP ( v0, v );
advect ( N, 1, u, u0, u0, v0, dt ); advect ( N, 2, v,
v0, u0, v0, dt );
project ( N, u, v, u0, v0 );
}

Pseudo code given in the paper, Real-Time Fluid Dynamics for Games:

while ( simulating )
{
  //get_from_UI ( dens_prev, u_prev, v_prev ); //mouse input, can be ignored for the moment
  velStep ( N, U, V, uPREV, vPREV, VIS, DT );
  densStep ( N, DENS, dPREV, U, V, DIFF, DT );
  drawDens ( N, DENS );
}

Appending button onclick function runs when appended

When I append a button with an onclick function, that same functions runs immediately. How do I keep the onclick function and make it not run when appended? Heres the code where it gets appended:

let button=document.createElement("button");
button.innerHTML=users[i].replace("user__","").replace("=","").substring(0,users[i].replace("user__","").replace("=","").length/2);
button.onclick=removeUser(button.innerHTML);
accounts.appendChild(button);

Why JSON.parse fails with this array-like string

I tried to JSON parse this

  let string = `[""test1, ""test2"]`;
  let array = JSON.parse(string);
  console.log(array[0]);

It’s fairly simple enough but I don’t understand what’s error message is supposed to tell

  Uncaught SyntaxError: Unexpected token t in JSON at position 3

unhandledrejection event.reason error object does not contain custom properties

In my TypeScript React app i’ve added the unhandledrejection event to the window to catch any unhandled promise rejections.

I am using custom error classes with additional properties. Any errors or failures within my app throws these.

It appears the event.reason property of the unhandledrejection event is missing properties from my extended error classes. I can’t find anything as to why this would be. Is this expected behaviour of the unhandledrejection event and is there a work around?

class CustomAppError extends Error {

    readonly otherProp: string;
    readonly name: string;
    readonly code: number;

    constructor(message: string, otherProp: string) {
      super(message);

    
      this.name = this.constructor.name;
      this.code = 500;
      this.otherProp = otherProp;

      const actualProto = new.target.prototype;
      Object.setPrototypeOf(this, actualProto);
    }
}


try {
  await somePromise();
}
catch {
  throw new CustomAppError('an error', 'additional prop');
}


window.addEventListener("unhandledrejection", (event: PromiseRejectionEvent) => {

console.log(event.reason.code); // undefined
console.log(event.reason.otherProp; // undefined

});