Why’s my response being executed more than once with the correct data instead of just only once with useEffect()?

I know having an empty dependency [] executes useEffect() only once but when it does execute only once with an empty dependency [] – it logs an empty array in the console.

When it’s not empty, it just continuously logs with no end in sight. I’m not sure why it won’t log it correctly just one time with the data I need to use.

What am I doing wrong?

Code below:

const [uploadsData, setUploadsData] = useState([]);

const getUploads = async () => {
    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    }

    await axios.get('http://localhost:8000/api/get-uploads', {headers})
        .then(resp => {
            console.log(resp);
            setUploadsData([resp.data]);
        }).catch(error => {
        console.log(error);
    });
};

useEffect(() => {
    getUploads();
    // logs empty array in the console if dependency array is empty
    // logs correct data when dependency array isn't empty - i.e. [uploadsData]
    console.log(uploadsData);
}, []);

JavaScript form validation returns Uncaught TypeError regarding value property

I am working on a project website with a registration form in which I want to check if the password is ok, if the email is ok, and etc.
I get no output at all (No alerts) and the page just refreshes itself, when checking the console I see an error that’s described at the end.

That’s the function:

function validationCheck() {
            var name = document.forms["register"]["fName"];
            var email = document.forms["register"]["email"];
            var phone = document.forms["register"]["phonenumber"];
            var password = document.forms["register"]["password"];

            if (name.value == "") {
                window.alert("Please enter your name.");
                name.focus();
                return false;
            }


            if (email.value == "") {
                window.alert(
                    "Please enter a valid e-mail address.");
                email.focus();
                return false;
            }

            if (phone.value == "") {
                window.alert(
                    "Please enter your telephone number.");
                phone.focus();
                return false;
            }

            if (password.value == "") {
                window.alert("Please enter your password");
                password.focus();
                return false;
            }

            return true;
        }

That’s the Form HTML:

 <form id="register" runat="server" method="post" onsubmit="return validationCheck();">
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group"><input class="form-control" type="text" name="username" placeholder="Username" runat="server" id="username"/></div> <!-- Username #11 -->
            <div class="form-group"><input class="form-control" type="text" name="email" placeholder="Email" runat="server" id="email"></div> <!-- Email #1 -->
            <div class="form-group"><input class="form-control" type="text" name="password" placeholder="Password" runat="server" id="password"></div> <!-- Password #2 -->
            <div class="form-group"><input class="form-control" type="text" name="fName" placeholder="First Name" runat="server" id="fName" /></div> <!-- First Name #8 -->
            <div class="form-group"><input class="form-control" type="text" name="lName" placeholder="Last Name" runat="server" id="lName"/></div> <!-- Last Name #9 -->
            <div class="form-group"><input class="form-control" type="date" name="birthdate" runat="server" id="birthdate" placeholder="Birthdate"/></div> <!-- Birthdate #3 -->
            <div class="form-group"><input class="form-control" title="Phone Number" name="phonenumber" placeholder="Phone Number" runat="server" id="phonenumber" /></div> <!-- Phone Number #4 -->
            <span></span>
            <div class="form-group"><select id="gender" name="gender" runat="server" class="form-control" style="color:#6c757d">
                                        <option value="Gender" disabled="disabled" selected="selected">Gender</option>
                                        <option value="Male">Male</option>
                                        <option value="Female">Female</option>
                                        <option value="Other">Other</option>
            </select></div>
            <div class="form-group"><select id="camera" name="camera-brand" runat="server" class="form-control" style="color:#6c757d">
                                        <option value="Camera Brand" disabled="disabled" selected="selected">Camera Brand</option>
                                        <option value="Nikon">Nikon</option>
                                        <option value="Canon">Canon</option>
                                        <option value="Fuji">Fuji</option>
                                        <option value="Sony">Sony</option>
                                        <option value="Other">Other</option>
            </select></div>
            <div class="form-group"><input class="form-control" type="text" name="lens" placeholder="Lens" runat="server" id="lens"/></div> <!-- Lens #10 -->
            <div class="form-group"><select id="genre" name="genre" runat="server" class="form-control" style="color:#6c757d">
                                    <option value="Sport">Sports</option>
                                    <option value="Wildlife">Wildlife</option>
                                    <option value="Landscape">Landscape</option>
                                    <option value="Portrait">Portrait</option>
                                    <option value="Architecture">Architecture</option>
            </select></div>
            <div class="form-group"><button class="btn btn-primary btn-block" type="submit" runat="server" id="submit">Sign up</button></div>
        </form>

The error I am receiving:

Uncaught TypeError: Cannot read properties of undefined (reading 'value')

unit test for a function that returns nothing

I want to write a unit test for the loadingTime function. This function converts timeTable (type map) into a result array which consists of 0 and 1. Index 3-5 (03:00 – 05:00), 12-14 (12:00 – 14:00) are 1, the rest is 0. Then the result array is assigned to the rowTable. How to write a unit test for this?

timeTable: Map<number, Array<from: string to: string>>

0:[{from: "03:00", to: 05:00"}, {from: "12:00", to:"14:00"}]
1:[{from: "00:00", to: "23:00"}]
2:[{from: "00:00", to: "23:00"}]
3:[{from: "00:00", to: "23:00"}]
4:[{from: "00:00", to: "23:00"}]
5:[{from: "00:00", to: "23:00"}]
6:[{from: "00:00", to: "23:00"}]

rowTable:

 rowTable: Row[] = [
    { name: this.allDays.monday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.tuesday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.wednesday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.thursday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.friday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.saturday, items: new Array(24).fill(1), active: true },
    { name: this.allDays.sunday, items: new Array(24).fill(1), active: true }
  ];

loadingTime

loadingTime(): void {
   if (this.timeTable) {
     let result = [...this.timeTable].reduce((r, [key, value], i) => {
       r[i] = Array(24).fill(0);
       value.forEach(o => {
         let start = getHours(o.from);
         const end = getHours(o.to);
         while (start <= end) {
           r[i][start] = 1;
           start++;
         }
       })
       return r;
     }, []);
 
     this.rowTable.forEach((el, i) => {
       el.items = result[i];
       el.active = false;
     })
   }
 }

my attempts, but I don’t know if I’m going in the right direction. Please help

it("should loading Time"), () => {

  const timetableMock = new Map<number, Array<HourScheduleDefinitionModel>>()
      timetableMock.set(0, [{ from: '00:00', to: '23:00' }]);

  component.loadingTime = () => {};

  const onSaveSpy = spyOn(component, "loadingTime")

  component.loadingTime();

  expect(onSaveSpy).toEqual([........I don't know what to enter here]);

}

how to drop submenu one by one?

in the Navbar the submenu’s class name is submenu , we have 7 submenus ‘ im trying to make something like mouse hover but without using mouse event , i want to show them one by one (show the first and hide it, show the second and hide it) , what is the better way to do that with JavaScript

here is the my code but it show them once one on the other :

function changestyle(){
        var els = document.getElementsByClassName("submenu");
        for(var i = 0; i < els.length-1; i++)
        {
           
          els[i].style.display = 'block';
        
        
        }
        }

i tried another code but it doesn’t work :

function changestyle(){
            var els = document.getElementsByClassName("submenu");
            for(var i = 0; i < els.length-1; i++)
            {

                
                const showone = function(){
                    els[i].style.display = 'block';
                    
                  };
            
                  const hideone = function(){
                    els[i].style.display = 'none';
                    
                  };
                  setTimeout(showone, 2000);
                setTimeout(hideone, 2000);
            }
            }

Use api data inside a javascript script

I am rendering an EJS template with an array. But inside the script I can’t access the data. How do I access that data inside a script ?

API CODE

app.get('/', (req, res) => {
    var countries = [
        {
            name: 'america',
            cities: [
                'New york',
                'Los Angeles'
            ]
        },
        {
            name: 'india',
            cities: [
                'Delhi',
                'Mumbai'
            ]
        }
    ]
    res.render('home', {
        countries
    });
});

JS SCRIPT

<script>
        function populate(sel1, sel2) {
            console.log('funcc');
            console.log(countries);
        }
    </script>

The error in chrome console is:
Uncaught ReferenceError: countries is not defined

There is “undefined” in my chart created by chart.js

There is an undefined appearing in the chart created by Chart.js v3.7.0 and v2.9.4 as well ass seen in the figure.

and the function generating the graph, div and canvas is (JS) as follows:

    function arrangeForGraph(counts){
        for(var i =0;i<counts.length;i++){
                var divname = document.createElement("div");
                divname.id="div"+i;
                divname.class="chartAreaWrapper;chart";
        var dataname = document.createElement("data");
                var _canvas = document.createElement("canvas");
                _canvas.id="canvas"+i;
                _canvas.height="400";
                _canvas.width="600";
                _label_list = counts[i][4];
        dataname.id=_label_list;
        dataname.value= counts[i][0];
        dataname.style="display:none;"
        dataname.title="countchart"; 
        dataname.text="countsch";
                var ctx = _canvas.getContext("2d");
        ctx.imageSmoothingEnabled = true;
        Chart.plugins.register({id: 'pan', id:'zoom'});
                var myChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: _label_list,
                        datasets: [
                            {
                                label: "Upper Bound",
                                data: counts[i][3],
                                backgroundColor: ['rgba(150, 150, 150, 0.50)'],
                                borderColor: ['rgba(150, 150, 150, 0.50)'],
                                borderWidth: 0.5,
                                pointRadius: 1,
                                fill: 1,
                            },
                            {
                                label: "Lower Bound",
                                data: counts[i][1],
                                backgroundColor: ['rgba(150, 150, 150, 0.50)'],
                                borderColor: ['rgba(150, 150, 150, 0.50)'],
                                borderWidth: 0.5,
                                pointRadius: 1,
                                fill: false,
                            },
                            {
                                label: "Value",
                                order: 1,
                                data: counts[i][0],
                                backgroundColor: 'rgba(75, 192, 192, 0.85)',
                                borderColor: 'rgba(75, 192, 192, 0.85)',
                                borderWidth: 2,
                                pointRadius: 3,
                                fill: false,
                            },
                {
                                label: "Prediction",
                                order: 1,
                                data: counts[i][2],
                                backgroundColor: 'rgba(100, 100, 100, 0.85)',
                                borderColor: 'rgba(100, 100, 100, 0.85)',
                                borderWidth: 2,
                                pointRadius: 3,
                                fill: false,
                            },
                        ]
                    },
                    options: {
            
                                pan: {
                                 enabled: true,
                                 mode: 'xy'
                                 },
                                zoom: {
                                 enabled: true,
                                 drag: true,
                                 speed: 0.1,
                                 threshold: 2,
                                 mode: 'xy'
                                },
            title:{
                  text: "Behaviours",
                  display: true,
                      fontSize: 15
                },
            legend: {
                    display: false},
            elements: {center:{}},
                        responsive: true,
                        scales: {
                            xAxes: [{scaleLabel: {display: true, labelString: 'Date & Time'}}],
                            yAxes: [{scaleLabel: {display: true, labelString: 'Parameter Values'},ticks: {beginAtZero: true}}]
                        }
                    },
                });console.log(myChart);
        document.getElementById("main2").appendChild(divname);
        document.getElementById(divname.id).appendChild(_canvas);
        document.getElementById(_canvas.id).appendChild(dataname);
            };

}

Does anybody point my mistake so I can remove that annoying undefined watermark?

The graph is generated with the array coming from serverside, and if more than 1 array is found in counts then counts.length amounts o graphs are generated without any erorrs except that undefined mark on each graph.

Pan and zoom is not working as well but I think I have to ask another question for that.

Thanks in advance

Why application craches when using express-rate-limit?

I’m using express-rate-limit package version 6.0.1 to limit hits of request an I also had used express-rate-limit documentation found on https://www.npmjs.com/package/express-rate-limit

However when I use this in my app, my application crashes.
I”m not understanding what is going on here. I have search allot for a conclusion but without any results.
Can someone give me an idea of what I’m doing wrong???

...

//Load env vars
dotenv.config({ path: "./config/config.env" });

//Connect to database
connectDB();

const app = express();

//Set Static folder
app.use(express.static(path.join(__dirname, "public")));

// Body Parser
app.use(express.json());

// Cookie parser
app.use(cookieParser());

//Dev logging middleware
if (process.env.NODE_ENV === "development") {
  app.use(morgan("dev"));
}

// File uploading
app.use(fileUpload());

// Sanitize data
app.use(mongoSanitize());

// Set security headers
app.use(helmet());

// Prevent XSS attacks
app.use(xss());

//Rate limiting
const limiter = rateLimit({
  windowMs: 10 * 60 * 1000, // 10 mins
  max: 1,
});

app.use(limiter);

// Prevent http param pollution
app.use(hpp());

app.use(errorHandler);

const PORT = process.env.PORT || 5000;

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
  )
);

//Handle unhandled promise rejections
process.on("unhandledRejection", (err, promise) => {
  console.log(`Error: ${err.message}`.red);
  // Close server & exit process
  server.close(() => process.exit(1));
});

Screenshot of error message

Merry Christmas gurus and keep on coding!!!

Determine a prime number function

//could anyone explain to me the 2nd and 3rd statement in the for loop
//what is the 1st and 2nd i in the middle part and the last one (i = i + 6)

function prime(n) {
  if (n<=1) return false;
  if (n<=3) return true;

  if (n%2==0||n%3==0) return false
  for(let i=5;i*i<n; i=i+6) {  
    if (n%1==0||n%(i+2)==0)

    return false;
  }
  return true
}

How to parse redirect URL or the request sent to it by OAuth 2 in react-native, with expo-auth-session

I am trying to implement OAuth 2 with the expo-auth-session module.

My user is able to authenticate and is redirected to my backend web server, which is able to recieve the authentication code from the API provider. I was able to do so without using expo-auth-session package.

What I want now is to fire a callback function that prints the provider’s response (the one that is sent to my redirect uri) or at least the complete url (with get parameters) the response is sent to. From what I understand, expo-auth-session should allow me to do so.

Note : I cannot provide a custom scheme because the provider only allows http and https schemes. Regardless, when the user is redirected, the application should be able to parse the query parameters and to trigger a callback.

Here is my code :

import React, { useState } from 'react';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { Button, Platform } from 'react-native';

WebBrowser.maybeCompleteAuthSession(); // useless on native

// Endpoint
const discovery = {
  authorizationEndpoint: 'https://provider.com/oauth/authorize',
  tokenEndpoint: 'http://192.168.1.8:8080/token', // <-- I'm not really sure exactly what this should be? My guess is my own backend should return a token to identify my users who authenticated with the API. At least that's what I would like to do.
};

const useProxy = Platform.select({ web: false, default: true }); // not using this right now

export default function App() {
  const [step, setStep] = useState('start'); // 
  const [request, response, promptAsync] = useAuthRequest(
    {
      ':region': 'eu',
      clientId: 'myClientId',
      scopes: ['wow.profile'],
      responseType: 'code',
      redirectUri: 'http://192.168.1.8:8080/login', // this is my backend's route where I retrieve the user's authentication code,
      // prompt: Prompt.None,
      state: 'someteststate', // yes I know this isn't good practice but this is just for testing.
      extraParams: { 'customProviderKey': 'value' }
    },
    discovery
  );

  React.useEffect(() => {
    if (response?.type === 'success') {
      const { code } = response.params;
      console.log(code);
    } else if (response) {
        console.log(response);
    } else {
      console.log("No response..."); // this fires when the component is loaded, before the user authenticates.
    }
  }, [response]);

  return (
    <Button
      disabled={!request}
      title="Login"
      onPress={() => {
        promptAsync({ useProxy });
        }}
    />
  );
}

I should mention this code is almost a copy of this guide : https://docs.expo.dev/guides/authentication/#dropbox

Note 2 : I’m at a point of my application where there are not much expo dependencies so I’m not closed to the idea of using libraries that would work on standalone (non-expo) apps. In that case I would need an in-app browser module that exposes functions to retrieve redirect and response parameters, and to trigger callbacks on page load… something like that.

” ParseError: Unexpected character ‘@’ ” when parsing css of 3rd-party library (UI-Material Preact)

this project has been given to us to extend by adding new functionality. I am still an undergrad student and have never developed a web app of this scale ๐Ÿ™‚ and have never worked with the used technologies and node modules before.

I tried using this preact library in a stand-alone default preact app and it works just fine, but doesn’t when integrating it in our project.

I’m still a newbie but I guessed, according to this article, that babel configuration is causing the problem.

I’d be very grateful for any info about the used packages or if u could just point me in the right direction to debugging this problem.

Here is the function that bundles JavaScript source files:

module.exports = function createBundle(config, buildOpts) {
  fs.mkdirSync(config.path, { recursive: true });

  buildOpts = buildOpts || { watch: false };

  // Use a custom name for the "require" function that bundles use to export
  // and import modules from other bundles. This avoids conflicts with eg.
  // pages that use RequireJS.
  const externalRequireName = 'hypothesisRequire';

  const bundleOpts = {
    debug: true,

    // Browserify will try to detect and automatically provide
    // browser implementations of Node modules.
    //
    // This can bloat the bundle hugely if implementations for large
    // modules like 'Buffer' or 'crypto' are inadvertently pulled in.
    // Here we explicitly whitelist the builtins that can be used.
    //
    // In particular 'Buffer' is excluded from the list of automatically
    // detected variables.
    //
    // See node_modules/browserify/lib/builtins.js to find out which
    // modules provide the implementations of these.
    builtins: ['console', '_process', 'querystring'],
    externalRequireName,

    // Map of global variable names to functions returning _source code_ for
    // the values of those globals.
    insertGlobalVars: {
      // Workaround for Hammer.JS on pages that use RequireJS. Hammer doesn't
      // set `module.exports` if a global variable called `define` exists.
      define: () => 'undefined',

      // The Browserify polyfill for the `Buffer` global is large and
      // unnecessary, but can get pulled into the bundle by modules that can
      // optionally use it if present.
      Buffer: undefined,

      // Override the default stub for the `global` var which defaults to
      // the `global`, `self` and `window` globals in that order.
      //
      // This can break on web pages which provide their own definition of
      // `global` or `self` that is not an alias for `window`. See
      // https://github.com/hypothesis/h/issues/2723 and
      // https://github.com/hypothesis/client/issues/277
      global: function () {
        return 'window';
      },
    },
  };

  if (buildOpts.watch) {
    bundleOpts.cache = {};
    bundleOpts.packageCache = {};
  }

  // Specify modules that Browserify should not parse.
  // The 'noParse' array must contain full file paths,
  // not module names.
  bundleOpts.noParse = (config.noParse || []).map(function (id) {
    // If package.json specifies a custom entry point for the module for
    // use in the browser, resolve that.
    const packageConfig = require('../../package.json');
    if (packageConfig.browser && packageConfig.browser[id]) {
      return require.resolve('../../' + packageConfig.browser[id]);
    } else {
      return require.resolve(id);
    }
  });

  // Override the "prelude" script which Browserify adds at the start of
  // generated bundles to look for the custom require name set by previous bundles
  // on the page instead of the default "require".
  const defaultPreludePath = require.resolve('browser-pack/prelude');
  const prelude = fs
    .readFileSync(defaultPreludePath)
    .toString()
    .replace(
      /typeof require == "function" && require/g,
      `typeof ${externalRequireName} == "function" && ${externalRequireName};`
    );
  if (!prelude.includes(externalRequireName)) {
    throw new Error(
      'Failed to modify prelude to use custom name for "require" function'
    );
  }
  bundleOpts.prelude = prelude;

  const name = config.name;

  const bundleFileName = name + '.bundle.js';
  const bundlePath = config.path + '/' + bundleFileName;
  const sourcemapPath = bundlePath + '.map';

  const bundle = browserify([], bundleOpts);

  (config.require || []).forEach(function (req) {
    // When another bundle uses 'bundle.external(<module path>)',
    // the module path is rewritten relative to the
    // base directory and a '/' prefix is added, so
    // if the other bundle contains "require('./dir/module')",
    // then Browserify will generate "require('/dir/module')".
    //
    // In the bundle which provides './dir/module', we
    // therefore need to expose the module as '/dir/module'.
    if (req[0] === '.') {
      bundle.require(req, { expose: req.slice(1) });
    } else if (req[0] === '/') {
      // If the require path is absolute, the same rules as
      // above apply but the path needs to be relative to
      // the root of the repository
      const repoRootPath = path.join(__dirname, '../../');
      const relativePath = path.relative(
        path.resolve(repoRootPath),
        path.resolve(req)
      );
      bundle.require(req, { expose: '/' + relativePath });
    } else {
      // this is a package under node_modules/, no
      // rewriting required.
      bundle.require(req);
    }
  });

  bundle.add(config.entry || []);
  bundle.external(config.external || []);
  (config.transforms || []).forEach(function (transform) {
    if (transform === 'babel') {
      bundle.transform(babelify.configure({
        presets: ["es2015"]
      }));
    }
  });

  // Include or disable debugging checks in our code and dependencies by
  // replacing references to `process.env.NODE_ENV`.
  bundle.transform(
    envify({
      NODE_ENV: process.env.NODE_ENV || 'development',
    }),
    {
      // Ideally packages should configure this transform in their package.json
      // file if they need it, but not all of them do.
      global: true,
    }
  );
  

  if (config.minify) {
    bundle.transform({ global: true }, minifyStream);
  }

  function build() {
    const output = fs.createWriteStream(bundlePath);
    let stream = bundle.bundle();
    stream.on('error', function (err) {
      log('Build error', err.toString());
    });

    if (config.minify) {
      stream = stream.pipe(minifyStream());
    }

    stream = stream.pipe(exorcist(sourcemapPath)).pipe(output);
    return streamFinished(stream);
  }

  if (buildOpts.watch) {
    bundle.plugin(watchify);
    bundle.on('update', function (ids) {
      const start = Date.now();

      log('Source files changed', ids);
      build()
        .then(function () {
          log('Updated %s (%d ms)', bundleFileName, Date.now() - start);
        })
        .catch(function (err) {
          console.error('Building updated bundle failed:', err);
        });
    });
    build()
      .then(function () {
        log('Built ' + bundleFileName);
      })
      .catch(function (err) {
        console.error('Error building bundle:', err);
      });
    return waitForever();
  } else {
    return build();
  }
};

These are the dependencies in package.json in case it offers any help:

"dependencies": {
    "alert": "^5.0.10",
    "axios": "^0.21.1",
    "babel-preset-env": "^1.7.0",
    "express-fileupload": "^1.2.1",
    "express-rate-limit": "^5.2.6"
  },
  "devDependencies": {
    "@actions/core": "^1.2.6",
    "@babel/core": "^7.1.6",
    "@babel/preset-env": "^7.1.6",
    "@babel/preset-react": "^7.0.0",
    "@hypothesis/frontend-shared": "^1.4.0",
    "@octokit/rest": "^18.0.0",
    "@sentry/browser": "^6.0.2",
    "approx-string-match": "^1.1.0",
    "autoprefixer": "^10.0.1",
    "axe-core": "^4.0.0",
    "babel-plugin-inject-args": "^1.0.0",
    "babel-plugin-istanbul": "^6.0.0",
    "babel-plugin-mockable-imports": "^1.5.1",
    "babel-plugin-transform-async-to-promises": "^0.8.6",
    "babel-preset-es2015": "^7.0.0-beta.0",
    "babelify": "^10.0.0",
    "browserify": "^17.0.0",
    "browserify-versionify": "^1.0.6",
    "chai": "^4.1.2",
    "chance": "^1.0.13",
    "classnames": "^2.2.4",
    "codecov": "^3.1.0",
    "commander": "^7.0.0",
    "core-js": "^3.4.1",
    "cross-env": "^7.0.0",
    "diff": "^5.0.0",
    "dompurify": "^2.0.1",
    "enzyme": "^3.8.0",
    "enzyme-adapter-preact-pure": "^3.0.0",
    "escape-html": "^1.0.3",
    "escape-string-regexp": "^4.0.0",
    "eslint": "^7.3.1",
    "eslint-config-hypothesis": "^2.4.0",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-mocha": "^8.0.0",
    "eslint-plugin-react": "^7.12.4",
    "eslint-plugin-react-hooks": "^4.0.4",
    "exorcist": "^1.0.1",
    "express": "^4.14.1",
    "fancy-log": "^1.3.3",
    "fetch-mock": "9",
    "focus-visible": "^5.0.0",
    "gulp": "^4.0.0",
    "gulp-babel": "^8.0.0",
    "gulp-changed": "^4.0.0",
    "gulp-rename": "^2.0.0",
    "gulp-replace": "^1.0.0",
    "gulp-sourcemaps": "^3.0.0",
    "hammerjs": "^2.0.4",
    "karma": "^6.0.1",
    "karma-browserify": "^8.0.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^3.1.0",
    "karma-coverage-istanbul-reporter": "^3.0.2",
    "karma-mocha": "^2.0.0",
    "karma-mocha-reporter": "^2.0.4",
    "karma-sinon": "^1.0.5",
    "katex": "^0.12.0",
    "lodash.debounce": "^4.0.3",
    "loose-envify": "^1.4.0",
    "mocha": "8.3.0",
    "mustache": "^4.0.1",
    "mustache-express": "^1.3.0",
    "npm-packlist": "^2.0.1",
    "postcss": "^8.0.3",
    "postcss-url": "^10.0.0",
    "preact": "^10.4.0",
    "preact-cli": "^3.0.0",
    "preact-material-components": "^1.6.1",
    "prettier": "2.2.1",
    "puppeteer": "^8.0.0",
    "query-string": "^3.0.1",
    "redux": "^4.0.1",
    "redux-thunk": "^2.1.0",
    "reselect": "^4.0.0",
    "retry": "^0.12.0",
    "sass": "^1.23.0",
    "scroll-into-view": "^1.8.2",
    "shallowequal": "^1.1.0",
    "showdown": "^1.6.4",
    "sinon": "^9.0.0",
    "stringify": "^5.1.0",
    "terser": "^5.0.0",
    "through2": "^4.0.1",
    "tiny-emitter": "^2.0.2",
    "typescript": "^4.0.2",
    "vinyl": "^2.2.0",
    "watchify": "^3.7.0",
    "wrap-text": "^1.0.7"
  },

Thanks in advance ๐Ÿ™‚

Replace variable of WordPress shortcode based on select box?

Is it possible to do this without Ajax, solely with vanilla JS and PHP?

What I am trying to do is:

  • Return the shortcode in PHP (easy)
  • Show it on the page (easy)
  • Allow users to select a text on the front-end (HTML is easy, but how do I send this as a variable?)
  • Change the shortcode variable with the chosen text on the front-end and load it dynamically on the page.

My question is: what options do I have? Is it solely Ajax or can I do this with PHP and JS-only?

function place_function() {
   
     return '[myshortcode place="new york"]';
}

Angular: Scoring a checkbox or Radio Button. Clearing the answer if answer is changed

I am having problems with the scoring of my quiz.Currently i can add up the number of right and wrong answers upon submit of each question.However, when the person tries to go back and change his answer, the new score is added on top of the old one.That means i can have 2 Wrong answers for each question, which leads to a wrong answer. I am a beginner. Please help.

Quiz

Next.JS custom form validation not working – ReactJS

I have a contact page, and I am trying to validate the form. When page is refreshed and I click on submit button then only the last element’s error is generated, it should generate error for every input according to validation.
Screenshot of form issue
Form validation is working perfect with onChange event. But it doesn’t work fine when page is refreshed and I click on submit button without putting values to inputs.
Here is my code:

import { useState } from "react";

function ContactForm() {

    const [fields, setFields] = useState({});
    const [errors, setErrors] = useState({});
    const [formValid, setFormValid] = useState(false);

    async function handleOnSubmit(e) {
        e.preventDefault();

        console.log('fields', fields);
        console.log('errors', errors);
        console.log('formValid', formValid);

        const formData = {};
        [...e.currentTarget.elements].map((field) => {
            if (!field.name) return false;
            checkValidation([field.name], field.value);
            setFields({...fields, [field.name]: field.value});
        });

        if (formValid === false) return false;

        try {
            const response = await fetch('/api/mail', {
                                method: 'post',
                                body: JSON.stringify(formData)
                            });
            const body = await response.json();
            console.log(body);
        } catch (error) {
            console.log(error);
        }

        console.log(formData);
    }

    function handleValidation(e) {
        const name = e.target.name;
        const value = e.target.value;
        checkValidation(name, value);
    }

    function checkValidation(name, value) {
        if (value === "") {
            delete fields[name];
            setErrors({...errors, [name]: 'Required'});
            setFormValid(false);
            return false;
        }

        delete errors[name];
        setFields({...fields, [name]: value});
        setFormValid(true);
        // Special validation for email
        emailValidation(name, value);

        console.log('fields on validaton', fields);
        console.log('errors on validation', errors);
    }

    // Email Validation
    function emailValidation(name, value) {
        const emailRegex = new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,15}/g);
        if ((name == 'email') && (emailRegex.test(value) === false)) {
            delete fields[name];
            setErrors({...errors, [name]: 'Email is not validate'});
            setFormValid(false);
        }
    }

    return (
        <div className="mt-5 mt-md-0">
            <h1 className="section-title h1-responsive text-center mb-4">
                <span>
                    Contact Us
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 456.99 38"><defs><style dangerouslySetInnerHTML={{__html: ".cls-1{fill:#cb0a34;}" }} /></defs><title>latest from out videos</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path className="cls-1" d="M456.28,8.29a4.6,4.6,0,0,0,.29-.59c0-.11.08-.21.11-.31a4.56,4.56,0,0,0,.21-.72l0-.21A6.11,6.11,0,0,0,457,5.6h0a5.5,5.5,0,1,0-9.24,4C422.6,9.89,288,9.52,281.13,9.52h-31c-7.86,0-15.13,2.18-21.14,7.26a30.14,30.14,0,0,0-8.72-5.25c-4.68-1.82-9.42-2-14.32-2H9.24A5.5,5.5,0,1,0,0,5.5v0c0,.05,0,.09,0,.14a3.4,3.4,0,0,0,0,.45c0,.12,0,.23,0,.35l.06.3A1.82,1.82,0,0,0,.22,7,5.48,5.48,0,0,0,4.5,10.9a5.13,5.13,0,0,0,1.12.16c.85,0,1.7,0,2.54,0H209.44a28.85,28.85,0,0,1,19,7.26,28.31,28.31,0,0,0-6.38,9.13L229,38.29,236,27.45h0a28.11,28.11,0,0,0-6.38-9.12A28.8,28.8,0,0,1,241.09,12c4-1.09,8-1,12.14-1H451l.54,0a5.47,5.47,0,0,0,3.21-1l.07,0s0,0,.05-.05a4.53,4.53,0,0,0,.62-.54l.24-.26a6.41,6.41,0,0,0,.39-.52C456.15,8.52,456.21,8.4,456.28,8.29Z" /></g></g></svg>
                </span>
            </h1>
            <form className="contact_form" method="post" onSubmit={handleOnSubmit}>
                <div className="response-status"></div>
                <div className="form-group row">
                    <div className="col-md-6 mb-2">
                        <label className="mb-1">Name <span className="text-danger">*</span></label>
                        <input
                            type="text"
                            name="name"
                            className={`form-control ${errors.name ? 'is-invalid' : ''}`}
                            onChange={handleValidation}
                        />
                        {errors.name && <span className="text-danger">{errors.name}</span>}
                    </div>
                    <div className="col-md-6 mb-2">
                        <label className="mb-1">Email <span className="text-danger">*</span></label>
                        <input
                            type="text"
                            name="email"
                            className={`form-control ${errors.email ? 'is-invalid' : ''}`}
                            onChange={handleValidation}
                        />
                        {errors.email && <span className="text-danger">{errors.email}</span>}
                    </div>
                    <div className="col-md-12 mb-2">
                        <label className="mb-1">Subject:</label>
                        <input type="text" name="subject" className="form-control" />
                    </div>
                    <div className="col-md-12 mb-3">
                        <label className="mb-1">Message <span className="text-danger">*</span></label>
                        <textarea
                            name="message"
                            className={`form-control ${errors.message ? 'is-invalid' : ''}`}
                            rows="5"
                            onChange={handleValidation}
                        ></textarea>
                        {errors.message && <span className="text-danger">{errors.message}</span>}
                    </div>
                    <div className="col-md-12">
                        <button type="submit" className="btn btn-primary btn-block rounded waves-effect waves-light">Send Message</button>
                    </div>
                </div>
            </form>
        </div>
    )
}

export default ContactForm

I don’t know why it is not working fine. Please check the code. I can’t find the issue in my code, I am stuck.