Why doesnt the table get populated with the api response?

Ok. I have tried debugging this for hours. I call a fetch api and have verified that it returns the correct response formatted in the correct way, with all the keys and in array format compatible with the map function. However, the table when rendered appears to be missing the content of the body. Any ideas?

import React, { useEffect, useState, useContext } from 'react';
import "../App.css";
import { UserContext } from '../UserContext';

export function Watchlist() {
  const { user, logout } = useContext(UserContext);
  const [watchlist, setWatchlist] = useState([]);
  useEffect(() => {
    fetch(`http://127.0.0.1:8000/watchlist?user_id=${encodeURIComponent(user.id)}`)
      .then(response => response.json())
      .then(json => {
        setWatchlist(json)
      }
      ).catch(error => console.error(error));
  }, [user]);
  return(
    <table>
        <thead>
            <tr>
            <th>Ticker</th>
            <th>Name</th>
            <th>Last Price</th>
            </tr>
        </thead>
        <tbody>
            {watchlist && watchlist.map((s) => {
            <tr>
                <td>{s.ticker}</td>
                <td>{s.name}</td>
                <td>{s.last_price}</td>
            </tr>})}
        </tbody>
    </table>
  );
};

Eraser completely makes the Canvas white

main.js:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let isDrawing = false;
let lastX = 0;
let lastY = 0;
const AXIS_LENGTH = 50; // Length of the axis lines
let mouseX;
let mouseY;

// history so we can always redraw
var points = []
var allPoints = []
var invertedX, invertedY

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function startDrawing(e) {
  isDrawing = true;
  [lastX, lastY] = [canvas.width - (e.pageX - canvas.offsetLeft), canvas.height - (e.pageY - canvas.offsetTop)];
  points = []
  allPoints.push(points)
  points.push([lastX, lastY])


}

function draw(e) {
  if (!isDrawing) return;

  const x = canvas.width - (e.pageX - canvas.offsetLeft);
  const y = canvas.height - (e.pageY - canvas.offsetTop);

  [lastX, lastY] = [x, y];
  points.push([lastX, lastY])

}

function stopDrawing() {
  isDrawing = false;
}


function clearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}

function drawAllPoints() {
  allPoints.forEach(drawPoints)

}

function drawPoints(points) {

  if (points.length) {
    ctx.save()
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 5;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(points[0][0], points[0][1]);
    for (var i = 1; i < points.length; i++) {
      ctx.lineTo(points[i][0], points[i][1]);
      ctx.stroke();

    }
    ctx.restore()
  }
}

function drawEverything() {
  clearCanvas()
  drawAxis();
  drawAllPoints()

}

function drawAxis() {

  mouseX = invertedX
  mouseY = invertedY
  // Draw vertical axis line
  ctx.save()
  ctx.beginPath();
  ctx.moveTo(mouseX, mouseY - AXIS_LENGTH / 2);
  ctx.lineTo(mouseX, mouseY + AXIS_LENGTH / 2);
  ctx.stroke();

  // Draw horizontal axis line
  ctx.beginPath();
  ctx.moveTo(mouseX - AXIS_LENGTH / 2, mouseY);
  ctx.lineTo(mouseX + AXIS_LENGTH / 2, mouseY);
  ctx.stroke();
  ctx.restore()
}


canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
canvas.addEventListener('touchstart', (e) => {
  e.preventDefault();
  startDrawing(e.touches[0]);
});
canvas.addEventListener('touchmove', (e) => {
  e.preventDefault();
  draw(e.touches[0]);
});
canvas.addEventListener('touchend', stopDrawing);
window.addEventListener('resize', resizeCanvas);
document.addEventListener("mousemove", function(event) {
  const mouseX = event.clientX;
  const mouseY = event.clientY;

  invertedX = window.innerWidth - mouseX;
  invertedY = window.innerHeight - mouseY;

  drawEverything()
});

When I tried to erase the canvas by clicking the erase button, the every stroke in the canvas becomes white. I also have a cross hair thing that shows where the stroke is to be drawn. The controls are inverted. I used if else for the draw and erase. I used white color for the stroke which makes as the eraser tool. But when I click the btn and tried to drag, everything turns white but again clicking the btn makes evrything turns black.

Material UI import leading to “You may need an appropriate loader to handle this file type.”

Getting the following compilation error on just adding an import statement for material UI button component.

Failed to compile.

./node_modules/@lit/reactive-element/decorators/query-async.js 10:56
Module parse failed: Unexpected token (10:56)
You may need an appropriate loader to handle this file type.
|   return (n, e) => t(n, e, {
|     async get() {
>       return await this.updateComplete, this.renderRoot?.querySelector(r) ?? null;
|     }
|   });

here is my import statement

import '@material/web/button/filled-button.js';

without that import , it works perfectly..

I am using "@material/web": "^1.4.1", dependency.

I am stuck in this.. How can i proceed here?

PS: i am new to react, apologies if i have done silly mistakes!

There is some way to apply a custom mask to a FormKit field? I want to write a custom mask

how can I add a mask to the value of this field while the user is typing?

<FormKit
  type="text"
  name="postalcode"
  label="Postal Code"
  placeholder="Insert a postal code"
  validation="required|length:9|matches:/^d{5}-d{3}$/"
/>

when the user inputs “123456”, the value should be masked to “12345-6” until it reachs the maxlength of 9 characters

I’ve tried with @input event, but it always ends with a infinite recursive call

Why is threejs lighting fun such as pointlight and ambientlight not working with version “three”: “^0.164.1”

I was doing my very first threejs small project with vite and threejs library

I added these light function in js file,

`// emit light evenly in all directions from specific point in space
const pointLight = new Three.PointLight( 0xff0000, 1, 100 );
pointLight.position.set(5, 5, 5);



// to spread the lighting across the entire scene
const ambientLight = new Three.AmbientLight(0xffffff);
scene.add(pointLight, ambientLight);`

Inside of package.json,

{
  "name": "three-demo",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "devDependencies": {
    "vite": "^5.2.0"
    
  },
  "dependencies": {
    "three": "^0.128.0"
  }
}

The problem is that the lighting function works perfectly with three dependencies “three”: “^0.128.0” but when changes to latest version “three”: “^0.164.1” and run npm install, then the lighting function not working

JavaScript extends

function Animal() {}

function Rabbit() {}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

class Rabbit extends Animal {}

console.log(Object.getPrototypeOf(Rabbit) === Animal);

Why do they say these two ways are the same, but there is this difference

Why a string that has persian/arabic and English characters, was messed up in browser view?

I’m coding an ASP.NET core application. I read a record of SQL database and I want to show it in my html page through a Jquery function. It’s a part of my code:

//some code...

    <script charset="utf-8" type="text/javascript">
       $(document).ready(function () {
         var materialname = [];
         
         @if (Model.Count() != 0)
         {
            foreach (var item in Model)
            {
              @:console.log('name: ' + '@item.material.StoreName');
              @:materialname.push('@item.material.StoreName');

            } 
         }
       });
   </script>

When I run this code, it’s showed an incorrect string in console.
for example, StoreName in DB is:

enter image description here

but it is showed in console like this:

 name: &#x645;&#x62D;&#x635;&#x648;&#x644; &#x62F;&#x633;&#x62A;&#x647; AB &#x627;&#x646;&#x62F;&#x627;&#x632;&#x647; 5mm

How can I correct this and show a right encoding char?

react-pdf – production build produces minified JS file with improper require paths

I’m using react-pdf to render a PDF file from a web URL. The app works fine when doing local development, but fails to render when doing a production build. The root of the issue is that the pdf.min.worker.js file produced by the build has hard-coded file paths in its require statements that reference the file system of the machine that did the build. For example:

// Note: my local computer account is "administrator"
require("/Users/administrator/code/pdf-test/node_modules/@babel/runtime/helpers/defineProperty.js").default

Obviously, this causes the requires not to be found because they reference development paths in a production build. Does anyone know how to fix this?

Things I’ve tried

  • Everything mentioned in this issue and none of them have worked

Code

How do I get the data from an xhttp download to a string variable in Javascript and use it in my app

Here’s what I’m trying to do: NOAA offers data from public datasets on all kinds of climate data. What I am trying to do, in a javascript-only solution, is download the station and station metadata files from NOAA (plain text positional files), parse the metadata file for weather stations with the data I want (precipitation, daily max temps, min temps, and mean temps. From those data I can download the weather data from a station, and plot it using Plotly.

I’ve tried many different methods with xhttp, but I always end up in the same place. This is typical of my efforts:

<script>
    xhttpStation.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       stationData = xhttpStation.responseText;
    };

    xhttpStation.open("GET", "https://www.ncei.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt", false);
    xhttpStation.send();
</script>

I can’t find a way to get from the .responseText to back outside the function and on my way with the data to make the dropdown select lists of the station ids. I have to be missing something, because the asynchronous nature of the xhttp call allows my code to fly on by without wating to get the data.

async function inside forEach [duplicate]

A newbie question – There is an async function inside a for loop and I want to keep collecting data and once done I want to use this information to do something. How do I perform this using a callback? I was able to achieve the same using async.whilist but I want to avoid it and understand basic callback better.

function kickoff() {
    xlData.forEach(function(data) {
                var ruleId = data.rule_id;
                asyncRequest(ruleId).then(function(result) {
                            results.push(result);
                });
    });
}

I want to avoid doing this

function kickoff() {
    async.whilst(
                function test(cb) {
                    cb(null, i<len);
                },
                function iter(callback) {
                    i++;
                    asyncRequest(ruleId).then(function(result) {
                                results.push(result);
                    });
                },
                function (err, result) {
                    //able to get stuff that I can work with
                    console.log(result.length);
                } 
    );  
}

How come the 2nd exit button is not fading in after clicking the 1st exit button?

The 1st exit button (.exitA) fades in without an issue.

The 2nd exit button (.exitB) should fade in after the curtain goes up.

It does not.

How do I fix this?

https://jsfiddle.net/8c4e129f/

.exitA,
.exitB {
  opacity: 0;
  transition: opacity 3s ease-in;
  transition-delay: 0s;
  pointer-events: none;
}

.exitA.visible,
.exitB.visible {
  opacity: 1;
  pointer-events: auto;
  cursor: pointer;
}




function showExit(containerSelector, exitSelector) {
    const container = document.querySelector(containerSelector);
    const closeButton = document.querySelector(exitSelector);
    container.classList.remove("hide");
    container.classList.add("slide");
    container.addEventListener("transitionend", function() {
      closeButton.classList.add("visible");
    });
  }


  function removePlayer() {
    videoPlayer.destroyPlayers();
  }

  function resetPage() {
    hideContainer(".video-containerA");
    // showContainer(".video-containerB");
    showExit(".video-containerB",".exitB");
    removePlayer();
  }

Javascript how to return native string symbol iterator when string not include “!”?

I have meet some problem , i want to return native string symbol iterator when string not include “!”

Object.defineProperty(
    String.prototype,Symbol.iterator,
                {
    writable: true, configurable: true, enumerable: false,
    value: function iterator(){
   
    var i, inc, done = false,str=this

    return {
   
    next() {

    if((str).includes("!")){
      do custom iterator
    }else {
        return native string iterator
    }
     } };
    } }
    ); 

Any pepole can help , thanks!

How to reload a site that was previously opened in js

im trying to refresh a url that is opened until it is canceled by the user manually

This is the actual code that i used – Used for an exploit in most chrome blocking extensions that unblock a website after cancel. your text

<html>
<script>

let site = prompt("Site?")
let open_site = window.open(site)
while (true)  {
window.open_site.reload()
}

</script>
</html>

Using Node.js, fetching a webpage is different from on the browser

I am trying to use fetch on Node.js, to fetch the page: https://finance.yahoo.com/quote/META

I can see on the browser it is at a price of $443.29

Also if I use view-source:https://finance.yahoo.com/quote/META on the browser and set Disable JavaScript to ON on Google Chrome’s dev tool, I can see the following content:

data-field="regularMarketPrice" data-trend="none" data-pricehint="2"
data-value="443.29" active><span>443.29

However, if I do a fetch using Node.js, or even if I go to Chrome’s dev tool and the Network tab, and reload the page, and then right click on the first network resource, and right click and choose

Copy -> as fetch (Node.js)

I can get the equivalent of what Google Chrome used:

    fetch("https://finance.yahoo.com/quote/META", {
          headers: {
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language":
              "en",
            "cache-control": "max-age=0",
            "sec-ch-ua":
              '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"macOS"',
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
          },
          referrerPolicy: "no-referrer-when-downgrade",
          body: null,
          method: "GET",
          mode: "cors",
          credentials: "include",
        });

However, I tried to do a JS match, and cannot get the 443.29 string, but instead, keep on getting this:

Fz(36px) Mb(-4px) D(ib)" data-symbol="META" data-test="qsp-price" 
data-field="regularMarketPrice" data-trend="none" data-pricehint="2" 
value="511.9" active="">511.90

and $511.9 was the price as of 2, 3 days ago. What is the correct way to get the price (even if it is delayed 20 minutes or a couple of hours, but not for a couple of days).

The Node.js I am using is v20.10.0, which should be quite update.

P.S. to make it into a runnable program, the following can fetch the data and match the price:

const fetch = require("node-fetch");

fetch("https://finance.yahoo.com/quote/META", {
  headers: {
    accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "en",
    "cache-control": "max-age=0",
    "sec-ch-ua":
      '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "same-origin",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
  },
  referrerPolicy: "no-referrer-when-downgrade",
  body: null,
  method: "GET",
  mode: "cors",
  credentials: "include",
})
  .then((res) => res.text())
  .then((data) => console.log([...data.matchAll(/511..{30}/g)]));

and it will show the price match for 511. but not if I change the 511 to 443 — then it will not be able to match anything. (note that because the price change, so you may need to change to the prices later on, or you can change the last line to:

  .then((data) =>
    console.log([...data.matchAll(/36px.*regularMarketPrice.{80}/g)])
  );

instead.