JS Arrow / Lambda Function Reported as “Not a Function” by onchange but ONLY if Name Matches Input Box Name in QuerySelector?

While using JS arrow functions, I noticed something very strange that if the name of the constant the arrow function is assigned to exactly matches the “name=” for an input field that the arrow function is selecting with querySelector, the “___ is not a function” error occurs if calling the arrow function’s constant from an onchange.

I’m sure I’m not smart enough to have found a JS bug, so:
Why is a “___ is not a function error” returned by the onchange if the constant name and “name=” field match exactly??

Am I somehow accidentally passing in the constant itself into the query selector? I feel like it’s a hardcoded string not a constant name.

Example:
Updating the “firstName” input will say not a function, but the “lastName” input does not.
Interestingly the not a function is only reported as not a function by the onchange, but if calling firstName() from the console works fine. JS was added in the head using defer.

In the example below, entering text into the firstName box and hitting tab will cause the onchange to fail as it doesn’t recognize the function, but entering text into the lastName box and hitting tab works fine, as the constant is called “notLastName” instead of “lastName”.. and I don’t understand why the first fails and the 2nd works..

A code snippet can be run below. Ignore the CSS.

“firstName()” directly into the console does work.

const firstName = () => document.querySelector('[name="firstName"]').value;
const notLastName = () => document.querySelector('[name="lastName"]').value;
/*  1. RESETS
    ==================================
    Used to to normalize things like box-sizing.
*/

*,
*:before,
*:after {
  box-sizing: inherit;
  box-sizing: border-box;
}

/*  2. VARIABLES
    ==================================
    The baseline styling for html elements.
*/

    :root{
        --standardPadding: 8px 16px;
    }

/*  3. HTML ELEMENTS
    ==================================
    The baseline styling for html elements.
*/

html {
    height: 100%;
    max-height: 100%;
    overflow: hidden;
    padding: 0;
}


body {
    background: linear-gradient(338deg, rgba(206,210,218,1) 16%, rgba(255,255,255,1) 100%);;
    height: 100%;
    max-height: 100%; 
    margin: 0;
    display: flex;
    flex-direction: column;
    color: #1a1a1a;
}

nav {
    background: radial-gradient( circle farthest-corner at 10% 20%,  rgba(37,145,251,0.98) 0.1%, rgba(0,7,128,1) 99.8% );
    color: rgba(255,255,255);
    font-size: 1em;
    font-family: Arial;
    padding: 4px 16px;
}

nav h1 {
    margin: 0;
    font-weight: normal;
}

form {
    display: flex;
    width: 300px;
    max-width: 100%;
    overflow: auto;
    flex-direction: column;
    background-color: white;
    padding: 20px;
    margin: 16px auto auto auto;
    border-radius: 6px;
    border-style: solid;
    border-width: 1px;
    border-color: rgba(0,0,0,0.1);
}

form label:last-of-type {
    margin-bottom: 0;
}

label {
    font-family: Nunito;
    color: #1a1a1a;
    margin-top: 4px;
    z-index: 1;
    padding-left: 8px;
    color: rgba(0,0,0,0.5);

}

label + input {
    margin-top: -24px;
}

input {
    font-family: Nunito;
    height: 54px;
    margin-bottom: 16px;
    border: solid 1px#ced4da;
    border-radius: .25 rem;
    padding: 32px 8px 16px 8px;
    font-size: 1rem;
    border-radius: 4px;
    /* padding: 16px 8px 8px 8px; */
}

input:focus{
    outline-color: dodgerblue;
}

input:active{
    outline-color: dodgerblue;
}

footer {
    margin-top: 16px;
    padding: 4px 16px;
    font-family: Nunito;
    background-color: white;
}

/*  4. CUSTOM
    ==================================
    Custom classes
*/

.invalid{
    outline: solid 2px darkred;
    border: none;
}

.valid{
    outline: solid 2px #2A9D8F;
    border: none;
}
    <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Input Test</title>
        </head>
        <body>
            <nav>
                <h1>
                    Input Test: First Box Fails After "tab", 2nd Works
                </h1>
            </nav>
            
            <form>
                <label for="FirstName">First Name</label>    
                <input type="text" name="firstName" value="" onchange='alert("First Name:" + firstName())''>
                
                <label for="lastName">Last Name</label>
                <input type="text" name="lastName" value="" onchange='alert("Last Name:" + notLastName())''>
           </form>
        </body>
    </html>

React – Pass form values as props during onclick

I am new to React JS, I am learning state management and event handlings by developing a form. I am developing a form where I want to send the form values as params to onclick, when I am doing the onclick I want the values from the form as parameters. I created a form and created a onchange to get the values from the input box and I created a onsubmit handler to console the values from the state. Which is in usual method. Instead of using usual method I need to get the [userName, dob] which is my form values as params. I tried a lot , but I am struggling to achieve the output by passing values as params through onclick, I saw a same scenario question , but in the solution they have used useRef. Is there anyway where I can achieve this without using useRef. Any one can assist me what I have to do to sort out this issue ? Thanks in advance. I have wrote down my current code where I have followed usual method.

export default function UserData() {
  const intialValues = {
    userName: "",
    dob: "",
  };

  const [values, setValues] = useState(intialValues);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    console.log("first", name);

    setValues({
      ...values,
      [name]: value,
    });
  };

  const onsubmitHandler = (e) => {
    console.log("Clicked");
    console.log({ ...values });
  };

  return (
    <div>
      <form>
        <input
          value={values.userName}
          onChange={handleInputChange}
          name="userName"
          label="Username"
        />

        <input
          value={values.dob}
          onChange={handleInputChange}
          name="dob"
          label="DOB"
        />

        <button
          type="button"
          disabled={!values.userName || !values.dob}
          onClick={onsubmitHandler}
        >
          Submit
        </button>
      </form>
    </div>
  );
}

What are alternative methods for left side optional chaining in Javascript?

Being that in Javascript optional chaining on the left side of an assignment is not possible, as noted in this question and answer, what are some possible alternative methods to achieve this?

customer.details?.car = { make: 'Toyta' }
  1. I know you can do that with an if

    if (customer.details) {
        customer.details.car = { make: 'Toyota' };
    } else {
        customer.details = { car: { make: 'Toyota' } };
    }
    
  2. I tried with Logical OR || but I’m not sure it’s possible and the below is not correct

    customer.(details || {}).car = { make: 'Toyota' };
    
  3. Ternary with spread works

    customer = customer.details 
        ? { details: { car: { make: 'Toyota' } } }
        : { ...customer, details: { car: { make: 'Toyota' }}};
    

Are there any other methods?

Child component useEffect not triggering on props change

I made a functional component and passed a JSON object to it as a prop, but it does not update on the parent’s state change. how to update child from the parent by passing object in prop.

the prop is an object like

fields: {
      circleName: {
        label: "Circle Name",
        placeholder: "Enter Circle Name",
        type: "text",
        required: true
      }
}

and this is my component

function FormBuilder({ fields, onChange, onSubmit, getActions }) {
    const [fieldsS, setFields] = React.useState(fields);

    React.useEffect(() => {
        setFields(fields);
    }, [fields]);

It works fine on the first render. but does not rerender on prop change.

Error in first computation of text width using HTML5 measureText() with a custom font

I’m building a 2D top-down turn-based soccer game. Every time you click a player of your team, a card is drawn on a side canvas. I’ve just started the code for such cards and as a preliminary action it just draws the template with the selected player’s name horizontally centered:

drawPlayerCard = (card, player) => {
    let ctx = this.leftUserContext;
    ctx.drawImage(card.template, card.position.x, card.position.y);
    const nameWidth = ctx.measureText(player.name).width;
    ctx.font = "12px fff";
    ctx.fillText(player.name, ((card.template.width - nameWidth) / 2) + card.position.x, (202 + card.position.y));
}

The font is a free font I downloaded and put in use through CSS

@font-face {
    font-family: fff;
    src: url(../font/fff-forward.regular.ttf);
}

body {
    font-family: fff;
    margin: 0;
    background-color: white;
}

and an old HTML trick I’ve found here on SO to get the font to preload:

<div id="TableSoccer">
    <canvas class="board" id="Field" width="1488" height="1008"></canvas>
    <canvas class="board" id="Players" width="1488" height="1008"></canvas>
    <canvas class="board" id="MouseEvents" width="1488" height="1008"></canvas>
    <canvas class="user left" id="LeftUser" width="200" height="1008"></canvas>
    <canvas class="user right" id="RightUser" width="200" height="1008"></canvas>
</div>
<div style="font-family:'fff'">&nbsp;</div> <!-- font preload -->

However, the first time I click on a player, the name on the card is centered using a default font size instead of the custom’s one, that still is correctly loaded and shown:

This is the result at the first click with custom font loaded:

enter image description here

This is the result at further clicks with custom font loaded:

enter image description here

This is the result at the first click with default font. I commented out the ctx.font = "12px fff" line and the resulting text it’s perfectly centered, so my assumption about the default font size used for the first measure is correct:

enter image description here

I think this has something to do with asynchronous loading of the font but I don’t get why because the font is actually loaded and shown.

What am I missing?

Function property is different from it’s this [duplicate]

Recently I noticed that there is not a difference between these two snippets.

function step() {
  if (!this.counter) this.counter = 0;
  return this.counter++;
}

console.log(step()); // -> 0
console.log(step()); // -> 1
console.log(step()); // -> 2
function step() {
  if (!this.counter) this.counter = 0;
  return this.counter++;
}

step.counter = 10;

console.log(step()); // -> 0
console.log(step()); // -> 1
console.log(step()); // -> 2

Why does setting a function property not affect it’s this?

how to check for duplicate entries and retain an entry during movement using angular13

i am using angular13 in my application. in the given demo, i am able to move the items completely from left to right and vice versa, so duplicate records are avoided, but here now,

  1. i must move the records from left to right and must keep a copy of that in left also.
  2. so next time when i am trying to move the same record to the right again, i must get an alert message, so that movement can be avoided.
  3. if i click on right item to move to left, both the items ae getting selected, i mean in both left side and right side, i want the item to be selected in which side i choose that item.

HTML:

<div class="card">
  <div class="card-header" id="headingBasicAgentsGroupView">
    <a
      href="javascript:void(0);"
      class="d-block h5 mb-0"
      data-target="#basicAgentsGroupView"
      aria-expanded="false"
      aria-controls="basicAgentsGroupView"
      >Group View</a
    >
  </div>
  <div
    class=""
    id="basicAgentsGroupView"
    aria-labelledby="headingBasicAgentsGroupView"
    data-parent="#basicTabAccordion"
  >
    <div class="card-body" id="agents-group-view">
      <div class="row">
        <div class="col">
          <div class="form-group">
            <h6 class="font-weight-bold">Group</h6>
          </div>
        </div>
        <div class="col-2"></div>
        <div class="col">
          <div class="form-group">
            <h6 class="font-weight-bold">Not in Group</h6>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <div class="card shadow-sm border-0 swap-list list-left">
            <div class="card-header border-bottom-0 rounded-top">
              <div class="row">
                <div class="col d-flex align-items-center">
                  <input
                    type="text"
                    name="SearchDualList"
                    class="form-control"
                    placeholder="Search"
                  />
                </div>
              </div>
            </div>
            <div class="card-body overflow-auto py-0">
              <ul
                class="list-group list-group-flush"
                *ngFor="let child of agentInView"
                name="agentInGroup"
              >
                <li
                  class="list-group-item {{
                    isInActiveItems(child) ? 'active' : ''
                  }}"
                  (click)="toggleActiveItem(child)"
                >
                  {{ child.value }}
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div
          class="col-2 d-flex flex-column justify-content-center list-arrows"
        >
          <button
            type="button"
            class="btn btn-outline-primary my-3 move-right"
            (click)="moveToTheRight()"
          >
            Move Right
          </button>
          <button
            type="button"
            class="btn btn-outline-primary my-3 move-left"
            (click)="moveToTheLeft()"
          >
            Move Left
          </button>
        </div>
        <div class="col">
          <div class="card shadow-sm border-0 swap-list list-right">
            <div class="card-header border-bottom-0 rounded-top">
              <div class="row">
                <div class="col d-flex align-items-center">
                  <input
                    type="text"
                    class="form-control"
                    placeholder="Search"
                  />
                </div>
              </div>
            </div>
            <div class="card-body overflow-auto py-0">
              <ul
                class="list-group list-group-flush"
                *ngFor="let child of agentNotinView"
                name="agentNotInGroup"
              >
                <li
                  class="list-group-item {{
                    isInActiveItems(child) ? 'active' : ''
                  }}"
                  (click)="toggleActiveItem(child)"
                >
                  <input type="text" [(ngModel)]="child.value" />
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

TS:

  public moveToTheRight(): void {
    this.move('agentInView', 'agentNotinView');
  }

  public moveToTheLeft(): void {
    this.move('agentNotinView', 'dummyArray');
  }

  // moving function
  public move(from: string, to: string): void {
    this[from] = this[from].filter((item: any, i: number) => {
      if (this.isInActiveItems(item)) {
        this[to].push(item);
        this.agentInView.push(item);
        return false;
      } else {
        return true;
      }
    });

    // if needed
    // sort if needed
    this[to].sort((a, b) => (a.id > b.id ? 1 : -1));

    // clean active items after action
    this.activeItems.length = 0;
  }

  public toggleActiveItem(eventItem: any): void {
    if (this.activeItems.find((item) => item === eventItem)) {
      this.activeItems = this.activeItems.filter((item) => item !== eventItem);
      this.agentInView.push(eventItem);
    } else {
      this.activeItems.push(eventItem);
    }
  }

  public isInActiveItems(eventItem: any): boolean {
    return !!this.activeItems.find((item) => item === eventItem);
  }

Demo

TypeScript: Importing a module in a Typescript project?

I have some static data I am trying create a lookup table for so I have an object in a TS file:

newTSFile.ts

export declare module FontList { 
   export DEFAULT_DATA: {
       'james': {
           'age': '23'
        },
        'jack': {
           'age': '22'
        }
   }
}

then in my main TS file, I am importing as

import { FontList } from './newTSFile';

// 
console.log("font list: ", FontList)

however, it still can’t find the file when compiling with the error: Error [ERR_MODULE_NOT_FOUND]: Cannot find module .../FontList .
Not sure what I am doing wrong here in regards to importing

Code works perfectly on codepen but not in webstorm

The code that am trying in codepen worked, the same one does not work in webstorm.
Nothing seem to work no error showing when clicking on button,

Example

const email = document.querySelector('.user-input');
const submit = document.querySelector('.btn0');
const error = document.querySelector('.mail-error');

const showError = () => {
error.style.display = 'block';
};

if (submit) {
  submit.addEventListener('click', (e) => {
    e.preventDefault();
    if (!email.value.match(/^([A-Za-z0-9_-.])+@([A-Za-z0-9_-.])+.([A-Za-z]{2,4})$/)) {
       return showError();
    }
    document.getElementById("main0").style.display = "none";
    document.getElementById("main1").style.display = "block";
  });
}
<div id="main0">
  <input class="user-input" id="input-id" placeholder="Email" onblur="">
  <p class="mail-error" style="display: none;">Please enter valid email</p>
  <div class="btn0" id="btn0id" onclick="">NEXT</div>
</div>
<div id="main1" style="display:none;">
  <p> You now have access. <p>
</div>

How to catch value that caused exception

Is there any way to catch the value of what caused an exception to be thrown? I’m currently using a Nest global exception filter that catches just about everything (a very basic one, identical to the one on Nest’s documentation) and to show custom messages, I’m doing something like:


catch(exception, host) {
if(exception instanceof AnyErrorObjectHere) {
 // log a custom message
}
}

What if I want to know what caused that issue? If I tried to send an invalid value to my ORM or if I tried to parse something not parsable… Do my exception holds that value?

Calling one function with another function variables javascript [duplicate]

I am trying to learn JS internals.I am currently trying to print message “yo” both times using the two console.logs. I tried using call,bind or apply to see if it will help but it still doesn’t. On the execution stack it places func2 execution context above the func1 execution context. So, I was hoping it would take the func2.

var a = 'hello';

function func1() {
    console.log(a);
}

function func2() {
    var a = 'yo';
    func1();
    console.log(a);
}

func2();

I know that if we put it as a nested function it will work.

var a = 'hello';

function func2() {
  var a = 'yo';

  function func1() {
    console.log(a);
  }
  func1();
  console.log(a);
}

func2();

Is there a way to print the internal message without declaring a function inside like the 2nd example without passing a variable to func1?

I think the reason why the first is not working is because this refers to the window but slightly confused due to Execution Context placed over the Execution Stack.

is there any way to select all the fields data from the table except one field data using nodejs

I want to fetch all the fields data but don’t want to specify the fields name and don’t want to create a view.
I have tried

WITH orderschema as 
(SELECT array_to_string(ARRAY(SELECT c.column_name
        FROM information_schema.columns As c
            WHERE table_name = 'orders' 
            AND c.column_name NOT IN('Quantity')
    ), ','))
    SELECT * from orderschema

but this is returning the data as a single string.
is there any way to exclude the field directly in psql?