How do I prevent a form from submitting and display a message if the email and password don’t match?

<?php
session_start();
if(isset($_POST["button"])) {
    $email = $_POST["email"];
    $lozinka = $_POST["lozinka"];

    $korisnik = new Korisnik(1, "", "", $email, $lozinka);
    $odgovor = Korisnik::prijava($email, $konekcija);
    $rez = $odgovor->fetch_array(MYSQLI_ASSOC); 
    $lozinka = $rez["lozinka"] ?? " ";
    $korisnikID = $rez["korisnikID"] ?? " ";
    $greska = 0;

    if (!password_verify($_POST["lozinka"], $lozinka)) {
        $greska = 1;
    } else {
        $_SESSION["korisnik"] = $korisnikID;
        setcookie("korisnik", $korisnikID, time() + 60*60*60);
        header("Location: glavna.php");
        exit();
    }
}

?>

[...]

<body>
        <form class="container" method="post" action="" id="forma" enctype="multipart/form-data" novalidate>      
            <input type="email" name="email" id="email" class="input" placeholder="Email" required>

            <input type="password" name="lozinka" id="lozinka" class="input" placeholder="Šifra" required>

            <div id="nepoklapase" <?php if ($greska == 1) {?> style="display:flex" <?php } else { ?> style = "display:none" <?php } ?> >
                <h5 class="crvena">Podaci se ne poklapaju</h5>
            </div>

                <button class="button" name="button" id="button" type="submit">Prijavi se</button>

        </form>
    </div>
    
<script>  
    [getDocumentById code]
    
    form
  .addEventListener(
    'submit',
    (event) => {
        email.classList.toggle('error', !email.validity.valid);
        lozinka.classList.toggle('error', !lozinka.validity.valid);
        faliemail.classList.toggle('promeni', !email.validity.valid);
        falilozinka.classList.toggle('promeni', !lozinka.validity.valid);

      if(!email.validity.valid){
        event.preventDefault();
      }


      if(!lozinka.validity.valid){
        event.preventDefault();
      }

      <?php if ($greska == 1) { ?>
       event.preventDefault();
     <?php 
       $greska == 0;
       } ?>
    }
);

[...]

</script>

I’m trying to set the value of greska to 1 when the email and password of the user don’t match so that the nepoklapase div becomes displayed with the proper message and the form stops from submitting. With the code I have the form keeps submitting and the message stays displayed.

I sort of get what the problem with displaying the message is, the value doesn’t reset and I think I can solve that later, but I can’t get the form to stop submitting. How do I do that?

setInterval does not apply state changes until timeout ends

I’m trying to fetch data from a service and when any of states below changed, i want to clear the interval and keep going with new states

Tried this code but it didnt help.

 useEffect(() => {
        if(autoRefresh) {
            let intervalCall = setInterval(getTaskElements,6000);
            return () => {
                // clean up
                clearInterval(intervalCall);
            };
        }
    }, [changes, paging, taskParams, sorting, language,autoRefresh]);

Detect if phone locking feature is enabled or not

Using javascript in a web page, how to know if the user has enabled or not the security feature that locks his phone ?

That’s, the state of the locking feature, not the state of the lock it-self.

The purpose is to prevent a user from logging into the web application if they have not secured their device.

I could not find any browser API that could provide this.

INSTAGRAM API Problem Object with ID ‘search’ does not exist

I’m facing an issue about Instagram API I generated access token from Instagram but when I want to retrieve data from search query for example I put query Cristiano I get an error

{ "error": { "message": "Unsupported get request. Object with ID 'search' does not exist, cannot be loaded due to missing permissions, or does not support this operation", "type": "IGApiException", "code": 100, "error_subcode": 33, "fbtrace_id": "ALThvLkMplhGjZBNOE56FTK" } }

retrieve data from API for example name username picture ..

Disabled toggle button when other toggle button is clicked

I have 3 toggle buttons that are called the same function.

HTML:

<button id="gen"  type="button" onchange='relasi("Gen")' > 1 </button>
<button id="imp"  type="button" onchange='relasi("Imp")' > 2 </button>
<button id="agr"  type="button" onchange='relasi("Agr")' > 4 </button>

I set my toggle button value like this:

let togButton = false;

Relasi() function:

function relasi(type) {
  if(togButton = !togButton){   //this means that the user had clicked the button so the value changed
       if(type === "Gen"){
         // set other button than Gen button disabled
       }
       if(type === "Imp"){
         // set other button than Imp button disabled
       }
       if(type === "Agr"){
        // set other button than Agr button disabled
       }
  } else {
      // this means that user hasn't clicked the button OR had clicked the same button twice
     // set ALL the buttons to enable
  }
}

Here is what I’m trying to achieve:

A toggle button that when user hasn’t clicked the button yet, the button value will be false. When user clicked the button, the value will change to true. And then, when the user clicked the button again the value will return to false (back to the original assigned value). This goes on and on.

At the same time, while one toggle button is in the state of true, I want the other toggle buttons to be disabled. This means that user only can click one button and make that button value true. To enable back other toggle buttons, user needs to click the true button again to make it false.

Hope my explanation is understandable. How can I achieve this using Vanilla Javascript?

D3 Masks Breaking when added to vertical line

I’m running into the following issue with masks in D3 that I’ve been quite perplexed by: adding masks to vertical lines makes them disappear: when I set a mask as an attribute as I would for any D3 object, rather than this mask being applied, the entirety of the line disappears!

See the following minimal example, where I construct 3 lines. notvertlineMask is a line that isn’t vertical, and appending the mask to it behaves as desired. vertlineMask is a vertical line with the mask appended to it. It does not render. (note: it is not within a region that would evevn be affected by the mask that we add, which is a circle of radius 20 at (400,400)). vertlineNoMask is a line identical to vertlineMask, except that it doesn’t have a mask appended to it. It renders perfectly.

http://jsfiddle.net/Sidney3/xzqatb83/8/

What might be causing this issue ?? I have a similar problem for horizontal lines, but not for lines that contain a horizontal component (i.e. the line from (0,0) -> (0,1) -> (1,1) will render just fine with a mask appended to it). There doesn’t seem to be anything inherently special about vertical/horizontal lines, so any insight would be appreciated! Output of code and code used in above example is also below for preservation reasons:

Output:
Output of code

Code:

$(document).ready(function() {

  var el = $(".mask"); //selector

  // Set the main elements for the series chart
  var svgroot = d3.select(el[0]).append("svg");
  var mask = svgroot
     .append("defs")
     .append("mask")
     .attr("id", "myMask");
  
  mask.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("width", 800)
    .attr("height", 500)
    .style("fill", "white")
    .style("opacity", 0.7);
    
  mask.append("circle")
    .attr("cx", 400)
    .attr("cy", 400)
    .attr("r", 20);
  var svg = svgroot
    .attr("class", "series")
    .attr("width", "800px")
    .attr("height", "500px")
    .append("g")
    .attr("transform", "translate(0,0)")
  var notvertlineMask = svg
    .append('line')
    .style("stroke","green")
    .style("stroke-width", 10)
    .attr("x1", 20)
    .attr("y1", 20)
    .attr("x2", 40)
    .attr("y2", 200) 
    .attr("mask", "url(#myMask)")
   var vertlineMask = svg //note: breaks
    .append('line')
    .style("stroke", "red")
    .style("stroke-width", 10)
    .attr("x1", 150)
    .attr("y1", 150)
    .attr("x2", 150)
    .attr("y2", 200) 
    .attr("mask", "url(#myMask)")
   var vertlineNoMask = svg
    .append('line')
    .style("stroke", "blue")
    .style("stroke-width", 10)
    .attr("x1", 150)
    .attr("y1", 150)
    .attr("x2", 150)
    .attr("y2", 200) 

    
  console.log("svg", svg)


});

How do I create multiple radial pie graphs on a single SVG using D3.js

I am currently trying to recreate a radial bracket for the 2023 NHL playoffs, the final design would look something like this NHL Radial Bracket.

I currently have the outermost ring completed for this but am unsure and currently unable to figure out a way to implement more radial rings past the first one I’ve made.

The code so far:

<!DOCTYPE html>
<html lang = "en">
   <head>
      <script src="https://d3js.org/d3.v7.min.js"></script>      
      <style>
        .wedge:hover {
          stroke-width: 15;
        }
      </style>
   </head>
    <body>
        <script>
            //creating the size of SVG area
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", 1200)
                        .attr("height", 800)
                        .style("border", "1px solid black");
            
            //moving svg area to center of page
            d3.select("svg")
              .append("g")
              .attr("transform", "translate(500,350)");
                
                //creating segments for the annulus/pie graph
                var playoffRoundOne = d3.pie()
                .startAngle(Math.PI / 4)
                .endAngle(Math.PI * 3)
                .padAngle(.03)
                .value((d) => d.wins)
                .sort(function (a, b) {
                    return b.value > a.value;
                });

                //dataset for playoff team, includes team name, team wins, and team logo
                var data = playoffRoundOne([{...}]);

                var colorScaleFill = d3.scaleOrdinal()
                                    .domain(["avalanche", "kraken", "stars", "wild", "knights", 
                                             "jets", "oilers", "kings", "bruins", "panthers", 
                                             "leafs", "lightning", "canes", "islanders", "devils", 
                                             "rangers",])
                                    .range(["#6F263D", "#99D9D9", "#006847", "#154734", "#B4975A", 
                                            "#041E42", "#FF4C00", "#A2AAAD", "#FFB81C", "#B9975B", 
                                            "#00205B", "#FFFFFF", "#CE1126", "#F47D30", "#CE1126", "#0038A8"]);
                
                //creating circles
                var arcGen = d3.arc()
                               .innerRadius(242)
                               .outerRadius(300);

                            //colors
                            d3.select("svg g")
                              .selectAll("path")
                              .data(data)
                              .enter()
                              .append("path")
                              .attr("d", arcGen)
                              .attr("stroke", (d) => colorScaleFill((d)))
                              .attr("stroke-linejoin", "round")
                              .attr("stroke-width", 3)
                              .attr("fill", (d) => colorScaleFill((d)))
                              .attr("class","wedge");

                                 
                  //logos
                  var imgs = svg.selectAll("image").data(data);
                            imgs.enter()
                                .append("image")
                                .attr("xlink:href", (d)=>(d.data.logo))
                                .attr("width", "30")
                                .attr("height", "40")
                                .attr("x", d => d3.pointRadial((d.startAngle + d.endAngle  - 0.02)/2 , (270))[0])
                                .attr("y", d => d3.pointRadial((d.startAngle + d.endAngle  - 0.02)/2 , (540)/2)[1])
                                .attr("transform","translate(488,330) rotate(1.2)");
  
      </script>
    </body>
</html>

React JS Bi-Directional Infinite Scroll using Intersection Observer API API call on both directions

I am implementing Bi-Directional Infinite Scroller in react js using Intersection Observer API that makes API calls in both direction, to optimize the rendering of the list I am storing contents of previousPage, currentPage & nextPage so it has a window of 3 if the user scrolls in either of the direction eg: Initial on page load it will call the api with page 0 and stores the response in state as users scrolls down it will append the new contents from the api to the state once the user passes page > 2(index starts of 0) it will flush the page 0’s content from the start and append page 3 at the end of the state. The same goes when user scrolls up until and the it passes the window scale it should remove the content from the last page and it should append the new page content to the start.
I have implemented the scrolling down logic but having issue implementing the scroll up logic.

import React, { useState, useEffect, useRef } from "react";
import axios from "axios";

function InfiniteScroller() {
  const [page, setPage] = useState(0);
  const [data, setData] = useState([]);
  const [init, setInit] = useState(0);
  const [loading, setLoading] = useState(true);
  const WINDOW_SCALE = 3;
  const observerRef = useRef(null);

  const fetchData = async (pageNumber) => {
    setLoading(true);

const res = await axios.get(
  `https://api.instantwebtools.net/v1/passenger?page=${pageNumber}&size=20`
);

// When the user scrolls down and if the current page goes out of windows scale flush the first page contents
if (page === init + WINDOW_SCALE) {
  setData((prevData) => {
    const newArr = [...prevData];
    const tempArr = newArr.slice(init + 20);
    return tempArr;
  });
  setInit((prevInit) => prevInit + 1);
}
// When the user scrolls up and if the current page goes out of windows scale flush the last page contents

    if (res.data.data.length) {
      res.data.data.map((dt) => {
        setData((prevData) => [...prevData, dt]);
        setLoading(false);
      });
    }
  };

  useEffect(() => {
    fetchData(page);
  }, [page]);

  const handleIntersection = (entries) => {
    console.log(page);
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (entry.target.id === "bottom") {
          // user has scrolled to bottom of page, fetch more data
          setPage((prevPage) => prevPage + 1);
        } else if (entry.target.id === "top") {
          // user has scrolled to top of page, fetch more data
        }
      }
    });
  };

  useEffect(() => {
    observerRef.current = new IntersectionObserver(handleIntersection, {
      threshold: "0.7",
    });
    observerRef.current.observe(document.getElementById("bottom"));
    page > 0 && observerRef.current.observe(document.getElementById("top"));
    return () => observerRef.current.disconnect();
  }, []);

  return (
    <div
      style={{
        height: "300px",
        overflow: "scroll",
        border: "1px solid black",
        margin: "5em",
        overflowX: "hidden",
        textAlign: "center",
      }}
    >
      {page > 1 && <div id="top" />}
      {data.map((passenger, i) => (
        <div key={i}>
          <p>Name: {passenger.name}</p>
          <p>Trips: {passenger.trips}</p>
        </div>
      ))}
      <div id="bottom" />
      {loading && <p>Loading</p>}
    </div>
  );
}

export default InfiniteScroller;

CodeSandbox: Sample Code

How do I keep the size of the header fixed and animate the title with a flip?

I’m a beginner and I wanted to replicate this site as a personal project: https://olhauzhykova.com/

I want the header section to remain the same size while the title changes. Also could anyone suggest how I can animate a top-down flip everytime the title changes?

HTML:

<html>
<head>
    <link rel="stylesheet" type="text/css" href="webcss.css">
    <script src="webjs.js"></script>
</head>
<body>
    <div class="header">
        <div class="logo"><img src="C:UsersengarDesktopWebsite 2logo.png"></div>
        <h1 class="title">Data Analyst</h1>
        <h1 class="title hidden">Mentor</h1>
        <h1 class="title hidden">Musician</h1>
        <h1 class="title hidden">Tech Enthusiast</h1>
    </div>
</body>
</html>

CSS:

.header {
    background-color: #f1f1f1;
    padding: 10px 40px; /* Change the padding value to adjust the width */
    border-radius: 20px; /* Round all corners */
    position: fixed;
    top: 2vh;
    left: 2vw;
    z-index: 999;
    transition: all 0.3s ease-in-out;
    display: flex;
    align-items: center;
  }
  
  .logo {
    display: inline-block;
    margin-right: 10px;
    border: 2px solid #333;
    border-radius: 50%;
    height: 50px;
    width: 50px;
    transition: all 0.3s ease-in-out;
  }

  img {
    max-width: 100%;
    max-height: 150%;
}
  
  .title {
    display: inline-block;
    font-size: 24px;
    margin: 0;
    font-weight: bold;
    white-space: nowrap;
    transition: all 0.3s ease-in-out;
  }
  
  .title.hidden {
    display: none; /* hide hidden titles */
  }
  
  .header:hover {
    transform: scale(1.05);
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
  }
  
  .header:hover .logo {
    transform: rotate(360deg);
  }
  
  .header:hover .title {
    margin-left: 10px;
  }
  
  .title.hidden {
    display: none;
  }

JAVASCRIPT

.header {
    background-color: #f1f1f1;
    padding: 10px 40px; /* Change the padding value to adjust the width */
    border-radius: 20px; /* Round all corners */
    position: fixed;
    top: 2vh;
    left: 2vw;
    z-index: 999;
    transition: all 0.3s ease-in-out;
    display: flex;
    align-items: center;
  }
  
  .logo {
    display: inline-block;
    margin-right: 10px;
    border: 2px solid #333;
    border-radius: 50%;
    height: 50px;
    width: 50px;
    transition: all 0.3s ease-in-out;
  }

  img {
    max-width: 100%;
    max-height: 150%;
}
  
  .title {
    display: inline-block;
    font-size: 24px;
    margin: 0;
    font-weight: bold;
    white-space: nowrap;
    transition: all 0.3s ease-in-out;
  }
  
  .title.hidden {
    display: none; /* hide hidden titles */
  }
  
  .header:hover {
    transform: scale(1.05);
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.3);
  }
  
  .header:hover .logo {
    transform: rotate(360deg);
  }
  
  .header:hover .title {
    margin-left: 10px;
  }
  
  .title.hidden {
    display: none;
  }

It would be great if you could suggest tutorials too!

TypeError: jsonArr[0].slice(…).reverse is not a function

I’m working with map coordinates in an array . I have:

 async function getGeoJSONArr() {
    const response = await fetch("http://localhost:3000/data");
    const jsonArr = await response.json();
    console.log("jsonARR", jsonArr);
    const reversedCoords = jsonArr[0].slice().reverse();

I want to get the first array element and reverse it for my leaflet map centerpoint.

I’m getting:

jsonARR [[-110.9617505,32.1853513],[-110.9611676,32.1852037]]
leaflet2.html:41 Uncaught (in promise) TypeError: jsonArr[0].slice(...).reverse is not a function

What am I doing wrong?

How to access JPL Horizons from javascript

I am trying to get astronomical data from JPL Horizons https://ssd.jpl.nasa.gov/horizons/ using javascript. I just get null data back.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
</head>
<body>
  <script>
    async function getText(file) {
      
      let myObject = await fetch(file, {
        method: "GET", // *GET, POST, PUT, DELETE, etc.
        mode: "no-cors", // no-cors, *cors, same-origin
      });
      let myText = await myObject.text();
      return myText;
   
    }
    
    jplString = "https://ssd.jpl.nasa.gov/api/horizons.api?format=text&COMMAND='499'&OBJ_DATA='YES'&MAKE_EPHEM='YES'&EPHEM_TYPE='OBSERVER'&CENTER='500@399'&START_TIME='2006-01-01'&STOP_TIME='2006-01-20'&STEP_SIZE='1%20d'&QUANTITIES='1,9,20,23,24,29'"


    myText= getText(jplString);

    console.log(myText);
  </script>
</body>
</html>

I have tried varying the method and mode, without success.

Any suggestions? Thanks in advance.

How can I intercept CTRL+V keypress and then alert what was pasted using JavaScript or jQuery?

I want to do the following:
User presses CTRL V while focused on the webpage
Page intercepts it and shows an alert with what the user has tried to paste

For example:
User has “foo” in clipboard
User presses CTRL V while focused on the webpage
Page shows an alert with “foo” in it

I am new to JavaScript, and I am not sure how can I implement this.
Any help will be appreciated. Thanks!

Getting “ReferenceError: (x) is not defined” after passing object via props in Vue3

I’ve a vue page & vue component. The vue Page, is getting data via Firebase and passing hte object as a prop to a component. When accessing the prop, within the components template area, I don’t get any errors. But when accessing the same prop in the script setup, I get ReferenceError. Could you help me understand what I am doing wrong?

Vue Page:

<script setup lang="ts">
import { getProfile, profile } from '/@src/composable/useProfiles'

const params = new URL(location.href).searchParams.get('id')

onMounted(async () => { 
  getProfile(params);
})

</script>

<template>
  <div class="page-content-inner">
    <Core-MyProfile v-if="!params" />
    <Core-UserProfile v-if="params" :profile="profile"/>
  </div>
</template>

Vue Component:

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";

const props = defineProps({
  profile: {
    type: Object,
    required: true,
  },
})

const sellPoints = props.profile.tribute.sell.current
const timePoints = props.profile.tribute.time.current
const usePoints = props.profile.tribute.use.current

const totalPoints = computed(
  () => sellPoints+timePoints+usePoints
);

</script>

Errors:


runtime-core.esm-bundler.js:38 [Vue warn]: Invalid prop: type check failed for prop "profile". Expected Object, got Undefined  
  at <CoreUserProfile key=1 profile=undefined > 
  at <Index onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > key="/profile?id=FC9gNTJ7D2hMaBcna9ILTGyxB3E2" > 
  at <BaseTransition mode="out-in" appear=false persisted=false  ... > 
  at <Transition name="fade-fast" mode="out-in" > 
  at <RouterView> 
  at <HomeLayout> 
  at <Profile onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <BaseTransition mode="out-in" appear=false persisted=false  ... > 
  at <Transition name="fade-slow" mode="out-in" > 
  at <RouterView> 
  at <App>

---

runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of setup function 
  at <CoreUserProfile key=1 profile=undefined > 
  at <Index onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > key="/profile?id=0TCIgQZxy5YJqyXNMZQqkBQhZv13" > 
  at <BaseTransition mode="out-in" appear=false persisted=false  ... > 
  at <Transition name="fade-fast" mode="out-in" > 
  at <RouterView> 
  at <HomeLayout> 
  at <Profile onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <BaseTransition mode="out-in" appear=false persisted=false  ... > 
  at <Transition name="fade-slow" mode="out-in" > 
  at <RouterView> 
  at <App>

---

Core-UserProfile.vue:12 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'tribute')
    at setup (Core-UserProfile.vue:12:34)
    at callWithErrorHandling (runtime-core.esm-bundler.js:155:22)
    at setupStatefulComponent (runtime-core.esm-bundler.js:7165:29)
    at setupComponent (runtime-core.esm-bundler.js:7120:11)
    at mountComponent (runtime-core.esm-bundler.js:5473:13)
    at processComponent (runtime-core.esm-bundler.js:5448:17)
    at patch (runtime-core.esm-bundler.js:5038:21)
    at mountChildren (runtime-core.esm-bundler.js:5234:13)
    at mountElement (runtime-core.esm-bundler.js:5143:17)
    at processElement (runtime-core.esm-bundler.js:5115:13)

Supertest+Jest does not send JSON payload

Here is my test function :

describe("Create a problem", () => {
    describe("Create a problem with valid data", () => {
      it("Should create a problem", async () => {
        const ProblemData = {
          title: "Pothole on Main Street",
          type: 2,
          description:
            "Large pothole on Main Street that is causing damage to vehicles",
          district: "Downtown",
          coordinates: "42.3584,-71.0598",
          address: "123 Main St, Boston, MA",
          photos: JSON.stringify(["pothole1.jpg", "pothole2.jpg"]),
          audio: "potholedowntown.mp4",
        };
        const payload = JSON.stringify(ProblemData);
        console.log(payload);

        await supertest(app)
          .post(`/problems/create`)
          .send(payload)
          .expect(400)
          .expect({
            message: "Problem created.",
          });
      });
    });
  });

The output of jest is –

> [email protected] test
> jest

  console.log
    {"title":"Pothole on Main Street","type":2,"description":"Large pothole on Main Street that is causing damage to vehicles","district":"Downtown","coordinates":"42.3584,-71.0598","address":"123 Main St, Boston, MA","photos":"["photo1.jpg","photo2.jpg"]","audio":"potholedowntown.mp4"}

      at src/tests/Problems.test.ts:60:17

 FAIL  src/tests/Problems.test.ts
  Problems
    Create a problem
      Create a problem with valid data
        ✕ Should create a problem (79 ms)

  ● Problems › Create a problem › Create a problem with valid data › Should create a problem

    expected { message: 'Problem created.' } response body, got {
      message: 'Invalid request body.',
      errors: [
        "must have required property 'title'",
        "must have required property 'description'",
        "must have required property 'type'",
        "must have required property 'district'",
        "must have required property 'address'",
        "must have required property 'coordinates'",
        "must have required property 'audio'",
        "must have required property 'photos'"
      ]
    }

As you can see, I have console logged the payload before sending it. I manually sent the console logged payload with Postman, and it worked. But for some reason, it is not working from supertest.

The field-empty errors come from Ajv validator middleware. The code for the validator is below –

export default function Validator(schema: Object) {
  return async (req: Request, res: Response, next: NextFunction) => {
    let valid: boolean = false;
    try {
      valid = ajv.validate(schema, req.body);
    } catch (err) {
      Logger("FILE : Validator.ts n" + String(err));
      res.status(500).json({ message: "Internal Server Error" });
      return;
    }
    if (!valid) {
      let errors = ajv.errors;
      let errMessages: (string | undefined)[] = [];
      if (errors) {
        errMessages = errors.map((error) => {
          return error.message;
        });
      }
      return res.status(400).json({
        message: "Invalid request body.",
        errors: errMessages,
      });
    }
    next();
  };
}

I also console logged the req.body on the validator function. it was empty.

Can anyone tell me why supertest is not sending the payload?

React pass component by props’s callback get error class constructors must be invoked with ‘new’

I have a simple page developed using React, the page has a Menu component which has a callback as props (targetPage), when the callback starts, a component is received and then it will be to insert into the page.

But this procedure fails, giving this error,

class constructors must be invoked with 'new'
basicStateReducer@http://localhost:3000/static/js/bundle.js:22501:45
updateReducer@http://localhost:3000/static/js/bundle.js:22610:26
...

this is source code

main app

import React, {useState} from 'react';
function App() {
    const [currentPage, setCurrentPage] = useState<any>();
    return (
        <div className="App">
                <Menu
                    targetPage={ (page: any) => {
                        setCurrentPage( page );
                    }}
                />
                <div id={'target-page'}>
                    { !!currentPage ? currentPage : (<img src={'https://localhost/logo'} /) }
                </div>
            </div>
    );
}
export default App;

menu component

import pageComponent from '.';
export const Menu = (props:{targetPage:any}) => (
    <div
        onClick={ clickEvent => {
            props.targetPage( pageComponent );
        }}
    >
        click
    </div>
)

component

import React from 'react';
export default class pageComponent extends React.Component<any, any> {
    state = {}
    constructor(props: any) {
        super( props );
    }
    render() {
        let content = (
            <div>Page</div>
        );
        return content;
    }
}

how can I does it get a component from a callback passed as porps?