Proper class format in modern ES

Is the following an acceptable way to initialize a class?

class Person {
    name = undefined; // or just `name` ?
    age = undefined; // or just `age` ?
    constructor(name, age) {
        Object.assign(this, {name, age});
    }
}
let p = new Person('tom', 10);

By that I mean, more specifically,

  • Is Object.assign(this, {...variables}) a good way to do all the this assignments?
  • Is it considered good practice to stick the variables at the top, or should they be placed within the constructor?
  • Is it better to explicitly set a variable to undefined or not? That is, is name = undefined; or name; preferable?

Typescript can’t find module of a referenced Project

I am trying to share code between 2 seperate Typescript projects.
To demonstrate this easily reproducable problem I created a minimal repository here (Including instructions to reproduce):
https://github.com/realdegrees/ts-function-reference/tree/master/project

You can check out the repo or the following code snippets.
The issue is that I can import e.g. interfaces and enums just fine and they work (ran the code and had the enums logged) but as soon as it’s a function I’m trying to import it doesn’t work anymore.

Running tsc works fine and throws no errors. You can even see that typescript resolves the module in question perfectly fine.

❯ tsc --traceResolution | grep 'reference/lib'
======== Resolving module '../reference/lib' from '/home/fasc/projects/reference- 
test/project/index.ts'. ========
Loading module as file / folder, candidate module location 
'/home/fasc/projects/reference-test/reference/lib', target file type 'TypeScript'.
File '/home/fasc/projects/reference-test/reference/lib.ts' exist - use it as a name 
resolution result.
======== Module name '../reference/lib' was successfully resolved to 
'/home/fasc/projects/reference-test/reference/lib.ts'. ========
======== Module name './lib' was successfully resolved to 
'/home/fasc/projects/reference-test/reference/lib.ts'. ========

However as soon as I try to start the project it’s the ‘ole
Error: Cannot find module '../reference/lib'

I have tried importing the index.ts, lib.ts directly and paths in tsconfig.ts.
References are setup correctly and it obviously works with types but for some reason not functions.

The project looks like this: [Image][1]

Files:

////////////// project/index.ts
// None of these work
import { foo as regularDirectImport } from '../reference/lib';
import { foo as regularIndexImport } from '../reference/index';
import {foo as pathsImport} from '@reference';
pathsImport();
regularDirectImport();
regularIndexImport();

/////////// project/tsconfig.ts
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist", 
    "esModuleInterop": true, 
    "forceConsistentCasingInFileNames": true, 
    "strict": true, 
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "@reference": ["../reference/index"]
    }
  },
  "references": [
    {
      "path": "../reference"
    }
  ]
}

////////// reference/index.ts
export * from './lib';

////////// reference/lib.ts
export const foo = () => {
    console.log('bar');
}

////////// reference/tsconfig.ts
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "baseUrl": "src",
    "declaration": true,
    "declarationMap": true,
    "composite": true
  }
}

I would die for some help, I have found several guides on how to import code from external typescript projects and they all mention that functions work as well but I just cannot get it work.
[1]: https://i.stack.imgur.com/KXOGc.png

Scroll to the top of modal window on button click

I’m building a site on WordPress using Elementor page builder, and I’m having trouble sending the user back to the top of a modal when clicking ‘next’ on a form.

Here’s the code I’ve been trying, and here’s the page it’s currently hosted: http://doortouk-co-uk.stackstaging.com/home/

(The modal can be opened by clicking the ‘Apply Now’ button at the bottom of the page, section 3, 4 and 5 have the longer sections that require the scroll to top functionality)

jQuery(document).ready(function () {
    jQuery('.e-form__buttons__wrapper__button-next').click(function(){
        jQuery(".dialog-widget-content").scrollTop(0);
        });
 })

Any help would be appreciated!

how to prevent multiple copies of React when developing library with Rollup?

I am developing tiny ui react library. I am using Rollup as a bundler. and i faced some strange issue:

react.development.js:1476 Uncaught Error: Invalid hook call. Hooks can only be called 
inside of the body of a function component. This could happen for one of the 
following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Here is my Rollup config:

import babel from "rollup-plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import external from "rollup-plugin-peer-deps-external";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
import typescript from "rollup-plugin-typescript2";
import peerDepsExternal from "rollup-plugin-peer-deps-external";

const packageJson = require("./package.json");

export default [
  {
    input: ["./src/index.ts"],
    output: [
      {
        file: packageJson.main,
        format: "cjs",
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    globals: {
      react: "React",
      "react-dom": "ReactDOM",
    },
    external: ["react", "react-dom"],
    plugins: [
      peerDepsExternal({ includeDependencies: false }),
      postcss({
        plugins: [],
        minimize: true,
      }),
      babel({
        exclude: "node_modules/**",
        presets: ["@babel/preset-react"],
      }),
      external(),
      resolve(),
      typescript({ useTsconfigDeclarationDir: true }),
      terser(),
    ],
  },
];

Component itself if very simple. Nothing special so i am skipping its code.
When i am publishing my lib to NPM – everything is working exactly as expected.

But when i am doing local instal with

npm i ../my-local-lib

I have this error in console:

react.development.js:1476 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

My expectation was that peerDepsExternal plugin will handle this case, but obviously i have messed up somewhere.

JS library for HTML formatting

Is there at least one good js library which can format an html code string?
I mean, i have a string variable with an html code in it. All i want is to call just one single function from the library to format this long ugly html line into the pretty html code and print it in the textarea.
I was searching on npmjs.com, but nothing was found, maybe i’ve missed something.

When using PHP to save a drop down menu selection it remembers the selection but doesnt trigger the onchange event changing the CSS when reloaded

So basically I need to have a PHP cookie I cannot use JavaScript to save the information even though I would like to do so. It saves the selection fine but when reloaded the selection doesnt trigger the onchange which im assuming is the problem. Due to this the CSS doesnt change and it loads into light mode even if dark mode is selected.

Here is my code (PHP/HTML):

<?php
$theme = null;
if (isset($_POST["setc"])) {
    $expire = time() + 60 * 60 * 24 * 30;
    setcookie("mycookie", $_POST["navyOp"], $expire);
    header("location: " . $_SERVER["PHP_SELF"]);
} else if (isset($_COOKIE["mycookie"])) {
    $theme = $_COOKIE["mycookie"];
}
?>
<div class="Button">
        <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
            <select name="navyOp" onchange="test(this);">
                <option selected="selected">Choose a Theme!</option>
                <option value="val1" <?php echo (!is_null($theme) && $theme === "val1" ? " selected" : ""); ?>>Light</option>
                <option value="val2" <?php echo (!is_null($theme) && $theme === "val2" ? " selected" : ""); ?>>Dark</option>
                <input name="setc" value="theme_setting" type="submit">
            </select>
        </form>
    </div>

The JavaScript:

window.test = function(e) {
  if (e.value === 'val1') {
    document.getElementById("container").style.cssText = "background-color: white;";
    document.getElementById("start").style.cssText = "border: 2px solid lightgrey; color: lightgrey; ";
    document.getElementById("choice").style.cssText = "border: 1px solid grey; ";
    document.getElementsByTagName("html").style.cssText = "background-color: white;";
      

  } else if (e.value === 'val2') {
    document.getElementById("container").style.cssText = "background-color: black;";
    document.getElementById("start").style.cssText = "border: 2px solid lightgrey; color: lightgrey; ";
    document.getElementById("choice").style.cssText = "border: 1px solid white;";
    document.getElementsByTagName("html").style.cssText = "background-color: black;";
  }
}

And CSS even though its not necessary:

#container{
    margin: 20px auto;
    background-color: white;
    height: 900px;
    width: 1850px;
    border-radius: 5px;
    box-shadow: 0px 5px 15px 0px;
    position: relative;
}

#start{
    font-size: 1.5em;
    font-weight: bolder;
    word-break: break-all;
    width:100px;
    height:150px;
    border: 2px solid lightgrey;
    text-align: center;
    cursor: pointer;
    position: absolute;
    left:875px;
    top:350px;
    color: grey;
}

html{
    background-color: white;
}

.choice{
    display: inline-block;
    width: 135px;
    text-align: center;
    border: 1px solid grey;
    border-radius: 5px;
    cursor: pointer;
    padding: 5px;
    color: grey;
}

Thank you for your time 🙂

How to clean input fields after another operations in a function in React?

I have a button and 2 input field and I am sending these input field values to backend. etc doing some operations. After doing operations in addCustomer function, I want to reset input fields but it is not working.
Here is the code:

function TableFooterPanel(props) {

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');

    const addNewCustomer = async (name, surname) => {
        await service.addCustomer(name, surname);
        props.funcParam();
        setFirstName('');
        setLastName('');
    }

    var isButtonDisabled = false;

    (firstName.length <= 3 || lastName.length <= 3) ? isButtonDisabled = true : isButtonDisabled = false;

    return (

        <>
            <Card className='buttonFooter'>
                <Form className='buttonFooter'>
                    <input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
                    <input type="text" placeholder="Last Name" defaultValue={lastName} onChange={e => setLastName(e.target.value)}></input>
                    <Button disabled={isButtonDisabled} onClick={() => addNewCustomer(firstName, lastName)} className='addButton'>Add</Button>
                    <label hidden={!isButtonDisabled} className='labelStyle'>Field lengths must be at least 4 character</label>
                </Form>
            </Card>

        </>

    );

}
export default TableFooterPanel;

Here everything is working good except

            setFirstName('');
            setLastName('');

they are not resetting or setting to another value. What is the reason for that and how can I achieve it ?

Monthly / Yearly pricing slider not refreshing on yearly selection

I have 2 days experience with HTML, CSS and JS on front-end development.

After reading lots I have been able to do the following. The thing is that it is refreshing when selecting the Monthly, but not on the Yearly, which is the one selected from the beginning.

This is the code I have been working on:

const switchMonthly = document.getElementById('switchMonthly');
const switchYearly = document.getElementById('switchYearly');
const flexy = document.getElementById('flexy');

switchMonthly.addEventListener('change', e => {
  flexy.classList.toggle('show-annually');
  flexy.classList.toggle('show-monthly');
})
switchYearly.addEventListener('change', e => {
  flexy.classList.toggle('show-monthly');
  flexy.classList.toggle('show-annually');
})
.show-monthly .price-box .monthly {
  display: none;
}

.show-monthly .price-box .annually {
  display: block;
}

.show-annually .price-box .monthly {
  display: block;
}

.show-annually .price-box .annually {
  display: none;
}
<input type="radio" id="switchMonthly" name="switchPlan" value="Monthly" />
<input type="radio" id="switchYearly" name="switchPlan" value="Yearly" checked="checked" />
<label for="switchMonthly">Monthly</label>
<label for="switchYearly">Yearly</label>
<div class="switch-wrapper">
  <div class="switch">
    <div>Monthly</div>
    <div>Yearly</div>
  </div>
</div>
</div>

<div id="flexy" class="flex">
  <div class="price-box">
    <p>
      <span class="monthly">
                         19.99
                    </span>
      <span class="annually">
                         199.99
                    </span>
    </p>
  </div>
</div>

As expressed, the problem is that on the “yearly” it always shows both pricing options.

How to set electron setproxy(http)

enter code here
newWin = new BrowserWindow({
width: 400,
height: 600,
frame: true,
maximizable: true,
webPreferences: {
devTools: true,
webviewTag: true,
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
preload: link
},
});

newWin.index = arg.index;
newWin.type = arg.type;

//I set the proxy to foreign here
newWin.webContents.session.setProxy({
    proxyRules: "http://129.226.148.192:3128",
}).then(() => {
    newWin.loadURL(`${arg.href}`);
}).catch((err) => console.error(err));

//Proxy login is done here 
newWin.on('login', (event, webContents, details, authInfo, callback) => {
    event.preventDefault();
    if (authInfo.isProxy) {
        callback('sub_1kni3wjb4g9i6pkhmbsz5qzd', 'stat900')
    }
});

Youtube API Update the image of a scheduled broadcast

Hello i’m using the youtube api insert method https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert to post a new broadcast to Youtube but i want to change the default image youtube is inserting on the broadcast here is the image youtube is giving by default

When i change the ‘thumbnail’ property on the livebroadcast it does not work can somebody please tell me how? and what’s the difference between slate and thumbnail please?

Is it possible to run Jest in Azure function runtime?

This might be a case of ‘you’re using the wrong tools for the job’ but I’m going to shoot my question anyways, because this is what I have to work with for now.

So, here goes:

I have to make relatively small applications that periodically run as functions in an Azure environment. These applications perform tasks like fetching data from an API and storing that data on a SFTP server. When I create these applications I use a TDD approach with Jest.

I’d like to react to any problems proactively and solve them before the function runs are scheduled. If I run Jest locally I would notice any of these problems but I’d like to automate this proces. Therefor I’d like to know if it’s possible to run these tests from an Azure function and have Azure Warnings notify me when one these runs fail.

What have I tried?

  • Created new function folder “Jest_Function”
  • Added an always failing test in a separate file.
/main_functions_folder
    /jest_function
        - index.js
        - function.json
        - failingTest.test.js
  • added the following code to index.js:
const { exec } = require('child_process');

function checkTests() {
  return new Promise((resolve, reject) => {
    exec('npm run test failingTest.test.js', (error) => {
      if (error) reject(error);
      else resolve();
    });
  });
}

module.exports = async function (context) {
  try {
    await checkTests();
  } catch (err) {
    context.log('tests failed!');
    throw err;
  }
};

Transforming the function and running it in the terminal results in expected behaviour:

const { exec } = require('child_process');

function checkTests() {
  return new Promise((resolve, reject) => {
    exec('npm run test failingTest.test.js', (error) => {
      if (error) reject(error);
      else resolve();
    });
  });
}

async function myTest() {
  try {
    await checkTests();
  } catch (err) {
    console.log('tests failed!');
    throw err;
  }
}

myTest();
tests failed!
node:child_process:399
      ex = new Error('Command failed: ' + cmd + 'n' + stderr);
           ^

Error: Command failed: npm run test failingTest.test.js
FAIL jest_function/failingTest.test.js
  ✕ short test (3 ms)

  ● short test

    expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

      1 | test('short test', () => {
    > 2 |   expect(0).toBe(1);
        |             ^
      3 | });
      4 |

      at Object.<anonymous> (jest_function/failingTest.test.js:2:13)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.227 s, estimated 1 s
Ran all test suites matching /failingTest.test.js/i.

    at ChildProcess.exithandler (node:child_process:399:12)
    at ChildProcess.emit (node:events:520:28)
    at maybeClose (node:internal/child_process:1092:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5) {
  killed: false,
  code: 1,
  signal: null,
  cmd: 'npm run test failingTest.test.js'
}

Azure

I deployed the function in Azure and manualy ran it. This resulted in a failing function as I expected, but for the wrong reason. It displayed the following error message:

Result: Failure Exception: Error: Command failed: npm run test failingTest.test.js sh: 1: jest: Permission denied

I’m not really sure where to go from here, any help or advice will be appreciated!

Remove Specific HTML Component After Successful Response With JavaScript Fetch API

I have an image component where the user has the option to delete the component (basically the image). The deletion in the MySQL database is handled by PHP, and I use the javascript fetch() API on form submission so that no hard refresh happens on the page when this happens. All of this works OK.

The Problem

The issue I have is there will virtually always be multiple instances of the component in the form, so after the fetch happens I obviously only want to remove the specific component that is tied to its related delete button. To do this I understand I need to use the remove() method on the component/HTML.

Normally with events such as click I would use something like e.target.closest('.element').querySelector('.child-element') but the issue I have is I need to link the remove() method to the e.submitter event, because I only want to remove that specific component that is linked to its delete button, and I want to do this after getting a 200 response to show the deletion happened in the database.

In the javascript below, the specific button used on delete submission is referenced using e.submitter, but I guess I need to find a way of storing that as a variable that I can then use in the if(response.status === 200) {} line of code ?

JavaScript

const forms = document.querySelectorAll('.upload-form-js'),
uploadDetailsComponent = document.querySelectorAll('.upload-details-component')

// URL details
const myURL = new URL(window.location.href),
pagePath = myURL.pathname

if (forms) {
    forms.forEach((form) => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            
            const formData = new FormData(this);
        
            if (e.submitter) {
                formData.set(e.submitter.name, e.submitter.value);
            }
        
            fetch(pagePath, {
                method: "post",
                body: formData
            })
                .then(function(response){
                return response.text(); // stops hard refresh of the page
            })
                .catch((e) => console.error(e));
        });

        if(response.status === 200) {

            // remove the specific component linked to the 'submit' event using the 'remove()' method

        }

    });
} // end of if (forms)

HTML There are multiple instances of the image component inside the form. In the HTML below I’ve just shown two instances

<section>
    <form class="upload-form-js" enctype="multipart/form-data" method="post">
        <div class="upload-details-component">
            <div class="image-wrapper">
                <img src="image.jpg" alt="image">
            </div>
            <button type="submit" name="delete" title="delete" value="12" class="dl-button">Delete</button>
            <input type="hidden" name="image-id" value="12">
        </div>
        <div class="upload-details-component">
            <div class="image-wrapper">
                <img src="image.jpg" alt="image">
            </div>
            <button type="submit" name="delete" title="delete" value="13" class="dl-button">Delete</button>
            <input type="hidden" name="image-id" value="13">
        </div>
    </form>
</section>

Calls to external APIs in sequence from Node.js

I’ve been struggling for a couple of weeks trying to find the best pattern to implement this, but didn’t end up with a proper solution.

I have a back-end written in Node.js, which is required to perform a sort of initialization to gather some data from external APIs, before it can work properly.

The calls to the external APIs must be performed sequentially, as the data result of one call is required by the next one.

Furthermore I have a couple of these sort of “calls pipeline” which can run independently, on separate “threads”.

The last complication is that I need all these calls pipelines to be finished before I can consider completed the initialization phase and I finally can start with the regular work for the back-end (i.e. exposing some APIs).

I have investigated several ways.

For sure, using synchronous calls is the first thing that comes to mind, but we all know it is strongly discouraged.
Also using async functions with await doesn’t seem to work to me.
Actually the .then() chain already implements a sort of pipeline, but still it’s not clear how to “wait until all the pipelines are finished”.
I tried with chain of .then() + Promise.allSettled(), but it didn’t work as expected (maybe the array of Promise you pass to this method must include all the Promises, even those you create inside each then()….).

I guess there should be some standard pattern / best practise to implement this, as to me it doesn’t seem to be so an uncommon scenario.

Any hint highly appreciated.

I’m using axios as library for the HTTP calls (GET and POST).

–Thomas

Event triggered when user Resets location services permission

I am thinking about using the navigator.geolocation.getCurrentPosition to store the latitude and longitude of a user, obviously after he has accepted to.

I thought about storing this on local storage so that whenever he opens the browser again he appears on that position.

However, I thought of the other case. What happens if he goes on Location and resets the permission, or decides not to share his location anymore. Is there any event or way I can see if he did that? Because if he did that I need to delete those stored keys and values of lat and long from Local storage.

Thanks.
enter image description here