Confused about this particular JavaScript way of expressing a function

I know there are different ways of declaring a function (or expressing it), however, I haven’t seen/used anything like this before (given, I am a “newbie” in the field). Can someone, please, explain how this particular function declaration works and when it is used? Can’t wrap my head around that “:” following function name!

const formSubmitHandler: SubmitHandler<IFormInputs> = () => {}

(Not sure if it has anything to do with typescript)

import './App.css';
import { useForm, SubmitHandler } from 'react-hook-form'

type IFormInputs = {
  email: string,
  password: string
}

const formSubmitHandler: SubmitHandler<IFormInputs> = (data: IFormInputs) => {
  console.log('the form data is', data);
}


const App = () => {
  const { register, handleSubmit, watch, formState: {errors}} = useForm<IFormInputs>()

  console.log(errors, 'this is an error explanation');
  console.log(watch('email'), 'watch the email variable');

  return (
    <div style={{padding: '2rem', border: '1px black solid'}}>
    <form onSubmit={handleSubmit(formSubmitHandler)}>
      <input defaultValue='[email protected]' {...register('email')}/>
      <br />
      {errors.password && <span>This field is required</span>}
      <br />
      <input {...register('password', { required: true })}/>
      <br />
      <br />
      <input type="submit" />
    </form>
    </div>
  )
}


export default App;  

Joi validation add rule only if property not undefined

I’m trying to implement the following validation rule using Joi.

Basically I have 2 properties a and b, I’d like to check that a is less than or equal to b only if b is not undefined.

Here is what I’ve tried so far:

const mySchema = Joi.object().keys({
    a: Joi.number().concat(Joi.number().when('b', { is: Joi.not(undefined), then: Joi.number().max(Joi.ref('b')).message('a should be less than or equal to b') })
    b: Joi.number() })

I get the following error message when testing the schema:

Cannot call allow/valid/invalid with undefined

Is it possible to terminate javascript code from runing from inside an async function

i want to terminate the javascript code from runing when a specific condition is satiesfied. But the problem is that the condition is inside an async function .

we can terminate the javascript from a normal function just by throwing an error but it does not work inside an async function.

if anyone can help me on this problem, it will be very helpful for me.
thanks in advanced.

Script must be prefetched but it doesn’t download

I want to prefetch one component for my application. And that’s how I’m trying to:

const Info = React.lazy(() => import(/* webpackPrefetch: true */ '@view/info/Info'));

Webpack use this magic comment to generate some links:

<link rel="prefetch" as="script" href="<href1>">
<link rel="prefetch" as="script" href="<href2>">
<link rel="prefetch" as="script" href="<href3>">

href1, href2 and href3 are working links and they lead to exsiting files.

But for some reason my chunk does not downloading until I try to use Info component.

What is the problem here?

i have a CSS button which i want to link to another html file without Javascript

i have a CSS button how to link to another html file without Javascript Note:
that i am not using html input or button html tags so i dont know how ,helpful if you would link a article or the solution code full
the html and css code below:

most of the code is just css animation from a site which is opensource and free

<!DOCTYPE html>
<html lang="en">
<body>

<h1 class="box-main"> Time :   9:30 AM </h1>
<h1 style="position:relative;  right:80px;  top:40px;" class="box-main">

</h1>

 <h1 class="box-main"> Date: 1 / 12 / 2021

 </h1>
 <h1 class="box-main"> Place: Random X and Z

 </h1>
</body>

    <meta charset="UTF-8">
    <title>Booking</title>
  <style>
    body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: right;
    background-color: black;
    }

    nav ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
    }

    nav ul li {
        --c: white;
        color: var(--c);
        font-size: 16px;
        border: 0.3em solid var(--c);
        border-radius: 0.5em;
        width: 6em;
        height: 3em;
        text-transform: uppercase;
        font-weight: bold;
        font-family: sans-serif;
        letter-spacing: 0.1em;
        text-align: center;
        line-height: 3em;
        position: relative;
        overflow: hidden;
        z-index: 1;
        transition: 0.5s;
        margin: 1em;
    }

    nav ul li span {
        position: absolute;
        width: 20%;
        height: 100%;
        background-color: var(--c);
        transform: translateY(150%);
        border-radius: 50%;
        left: calc((var(--n) - 1) * 25%);
        transition: 0.5s;
        transition-delay: calc((var(--n) - 1) * 0.1s);
        z-index: -1;
    }

    nav ul li:hover {
        color: black;
    }

    nav ul li:hover span {
        transform: translateY(0) scale(2);
    }

    nav ul li span:nth-child(1) {
        --n: 1;
    }

    nav ul li span:nth-child(2) {
        --n: 2;
    }

    nav ul li span:nth-child(3) {
        --n: 3;
    }

    nav ul li span:nth-child(4) {
        --n: 4;
    }
    .box-main {
            display: flex;
            justify-content: center;
            align-items: center;
            text-align: center;
            color: White;
            max-width: 80%;
            margin: auto;
            height: 80%;
    }

    text-big {
        font-size: 10px;
    }



  </style>
</head>

<body>

<nav>
  <li>
    <ul>



<nav>
  <ul>
    <li>
     this is the button text

     book
      <span></span><span></span><span></span><span></span>


</body>
</html>

Thanks in advance please ask if you need any more information

Best way to catch an error in Models? (Node.js + Sequelize)

Is there a simple way to catch an error in an API (server) that’s using Node.js and Sequelize (Models)? Here is my code (it uses async + await):

const router = express.Router()
const { Operations } = require('../models')

router.post('/operations/add', async (req, res) => {
    const operations = req.body
    await operations.create(operations)
    res.json(operations)
    console.log('op added!')
})

router.put('/operations/update/:id', async (req, res) => {
    const operationId = req.params.id
    const operationUpdatedData = req.body
    const operationById = await Operation.findOne({ where: { id: operationId } })
    const operationUpdated = await operationById.update(operationUpdatedData)
    res.json(operationUpdated)
    console.log('op updated!')
})

router.delete('/operations/delete/:id', async (req, res) => {
    const operationId = req.params.id
    await Operations.destroy({ where: { id: operationId } })
    res.send('op deleted!')
    console.log('op deleted!')
})

module.exports = router

This is how I handle an error in the client:

axios.post(`http://localhost:9000/operations/add`, data)
            .then(res => console.log(`op added! (${res.status})`))
            .catch(err => console.log(`wrong! (${err.response.status} )`))

I don’t want anything fancy, but feel free to try whatever you want!

Remove missing Images from array React.js

I have array of images coming from external API, I want to filter images which are broken before showing them on carousel. as you can see now I map every image and showing MissingImage component as unloader if image is missing, but in my situation sometimes there are more than half images not available on API. how can I skip images if they aren’t available before passing them to Carousel component?

          {images.map((img, i) => (
        <Dot
          key={i}
          type="button"
          onClick={() => {
            setThumbsPosition(i);
            goToSlide(i);
            setActiveSlide(i);
          }}
          active={activeSlide === i}
          ref={i === 0 && slideRef}
        >
          <SliderDotImage>
            <Img
              loading="lazy"
              src={[img.url.bigger]}
              unloader={<MissingImage small />}
            />
          </SliderDotImage>
        </Dot>
      ))}

react variable not changing

in my react app i have got two files and, when value of (number) is changing in file App.js
in Form.js is still the same. What am i doing wrong?

App.js

import * as React from "react";
import { Form } from "./Components/Form";

function App() {
  
  let number = 0;
  const onInputChange = e => number = e.target.value;
    // number is changing every time i type something in
  return (
    <>
      <input onChange={onInputChange}></input>
      <Form number={number} />
    </>
  );
}

export default App;

Form.js

import React from "react";

export const Form =({number}) =>
{
    return(
        <h1>{number}</h1>
    )
}

onbeforeunload function fires on browser back button

We´re using following code to show a loading-modal if the loading of next page takes to long.

window.onbeforeunload = function () {
    window.setTimeout(showLoader, 2000);
}

function showLoader() {
    var loader = '<div id="layoutLoadingModal" class="modal fade" role="dialog">' +
        '<div class="modal-dialog">' +
            '<div class="modal-content">' +
                '<div class="modal-body">' +
                    '<h1>Loading!</h1>' +
                '</div>' +
            '</div>' +
        '</div>' +
    '</div>';
    $("body").append(loader);
    $('#layoutLoadingModal').modal('show');
}

Unfortunately it also shows the modal if the user uses the browser back button or a button with history.go(-1);
Is there any way to tweek the code to prevent this?

cancel a mocked function in Jest and getting the original behavior after a single call

class MyService{
    async f1(args) {
        let out= await this.f2(args);
        ...
    }
}
...
// my test code:
MyService.f1.mockResolvedValueOnce([]);
await OtherService.f3(); // f1 is mocked and called in f3 and returns [] (everything is fine)
MyService.f1.mockRestore(); // trying to forget mocking f1 and getting the original behavior
MyService.f2.mockResolvedValueOnce([some data]); // I want original f1 to be called and mock the inner f2 but f1 is never called and I get undefined output from it

I’m trying to mock MyService’s functions only occasionally and after using the mocked version, forget that mocking and get the original behavior of them. But when I do it for once and restore that mock, I get undefined for the output of the mocked function and it’s actually never called.

Variables from different scripts are getting overridden

I am learning javascript and made a project where I have two canvases where I draw circles on. The scripts for each canvas is in its own file in the same folder. My problem is that for both of these scripts I am using the same variable names eg. radius and they seem to be shared between the two scripts.

I declare the variables as follows in the beginning of the file and then the function right afterwards.

const radius = 23;
const motionTrailLength = 30;
var context;
var xPos, yPos, maxX, maxY;
var dx = 2;
var dy = 2;

function init(canvas) {...}

I read that let and const “declared inside a { } block cannot be accessed from outside the block” so is there some way can wrap the script in those blocks to stop them from getting overridden?

Unable to get the value of a Promise . Error “Property ‘Choices’ does not exist on type ‘Promise'” [duplicate]

I have the following type script inside my ReactJs SPFx sharepoint online web part:-

import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
  IPropertyPaneConfiguration,
  IPropertyPaneDropdownOption,
  PropertyPaneDropdown} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';

import * as strings from 'ContactListWebPartStrings';
import ContactListApp from './components/ContactListApp';
import { IContactListProps } from './components/IContactListProps';
import { sp } from "@pnp/sp/presets/all";


export interface IContactListWebPartProps {
  department: string;
}

export default class ContactListWebPart extends BaseClientSideWebPart<IContactListWebPartProps> {
  private viewModeOptions: IPropertyPaneDropdownOption[] = null;
  public render(): void {
    const element: React.ReactElement<IContactListProps> = React.createElement(
      ContactListApp,
      {
        department: this.properties.department,
        context: this.context
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }
  public onInit(): Promise<void> {
    return super.onInit().then( _ => {
      sp.setup({
        spfxContext: this.context
      });
      const choice =  
      sp.web.lists.getByTitle('Contacts').fields.getByTitle('Department').get();
      this.viewModeOptions = choice.Choices.map((choice: string, idx: number) => 
      {
        return {
         key: idx,
         text: choice
        }
      })
   });
  }


  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneDropdown('department', {
                  label: 'Department',
                  options: this.viewModeOptions,
                  selectedKey: this.viewModeOptions[0].key,
                  disabled: !this.viewModeOptions
                 }),
              ]
            }
          ]
        }
      ]
    };
  }
}

but i am getting this error on choice.Choices.map:-

Property ‘Choices’ does not exist on type ‘Promise’

here is my web part details:-

{
  "@microsoft/generator-sharepoint": {
    "isCreatingSolution": true,
    "environment": "spo",
    "version": "1.12.1",
    "libraryName": "contact-list-webpart",
    "libraryId": "aa3dbbd0-0d6b-4cae-98b0-c29c37998c6e",
    "packageManager": "npm",
    "isDomainIsolated": false,
    "componentType": "webpart"
  }
}

How to flip image in jquery if the animation is at 0% and 50%?

I am try to make a running santa in my project.

How to loop transform: scaleX(1) and transform: scaleX(-1) when the animation start in 0% an 50%?

setTimeout(function(){
  //Enter your stuff here
  $('.animation').css("transform", "scaleX(1)")
}, 7500);  
.animation img {
  max-width: 100%;
}

.animation {
  width: 50px;
  position: absolute;
  bottom: 0;
  animation: example 15s infinite; 
  padding: 5px 9px 1px 0;
  border-top-right-radius: 20px;
  border-top-left-radius: 20px;
  transform: scaleX(-1)
}

@keyframes example {
  0%,
  100% {
    left: 0;  
    /* background: white; */
  }
  40% {
    /* background: green; */
  }
  30% {
    /* background: yellow; */
  }
  20% {
    /* background: orange; */
  }
  50% {
    left: 97%;  
    /* background: blue; */
  }  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="animation">
  <img src="https://lh3.googleusercontent.com/pw/AM-JKLX6lpuXIUQzWYC8J9vlnsS9Cb9irs-2kPKBM9XaugC4iDCag2-7w-zC7BSQls0Ea51YewUFFSJquODLZ8PfaAoqelAXOlCKmh0H7Cn9G5HcwX_u2XNT_tvr8ZD5as6He3dpMrrVH_-ZCaG1xctS_Tei=s512-no" alt="run santa run">
</div>

Codepen link: demo