How to programmatically validate a form before proceeding to the next step in a multi-step form using zod & react-hook-form

So i have a form in my app that has multiple steps, but at the moment if the user skips some steps and tries submitting, the form won’t submit because they skipped non-optional fields but the errors show at the previous steps so the user won’t know that some values aren’t filled in.

So what i was thinking of is, validating the form as the user progresses through the form so they cannot go to the next step without having completed the current ones.

What is a good approach on doing this using Zod?

My form:

"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Controller, useForm } from "react-hook-form";
import { z } from "zod";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { createApplication } from "@/app/applications/actions";
import { useUser } from "@clerk/nextjs";
import { useEffect, useState } from "react";
import { findUserByClerkId } from "@/app/actions";
import { Switch } from "@/components/ui/switch";
import {
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
  Form,
  FormDescription,
} from "@/components/ui/form";
import {
  Activity,
  Briefcase,
  Building2,
  Calendar,
  File,
  FileText,
  Hash,
  Link,
  MapPin,
  Paperclip,
  StickyNote,
  X,
  UserPlus,
  LinkedinIcon,
  User,
} from "lucide-react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import { Textarea } from "../ui/textarea";
import { uploads } from "./upload-files-page";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { BasicJobInfo } from "./form-fields/basic-job-info";
import { ApplicationDetails } from "./form-fields/application-details";
import { AdditionalInformation } from "./form-fields/additional-information";

type FormValues = z.infer<typeof formSchema>;

const formSchema = z.object({
  jobTitle: z
    .string()
    .min(2, { message: "Job Title must be at least 2 characters long" }),
  companyName: z
    .string()
    .min(2, { message: "Company Name must be at least 2 characters long" }),
  jobLocation: z
    .string()
    .min(2, { message: "Job Location must be at least 2 characters long" }),
  jobDescription: z
    .string()
    .min(5, { message: "Job Description must be at least 5 characters long" }),
  jobType: z.string(),
  applicationDate: z.string(),
  applicationStatus: z.string(),
  applicationLink: z.string().optional(),
  applicationNotes: z.string().optional(),
  jobReferenceNumber: z.string().optional(),
  applicationDeadline: z
    .string()
    .optional()
    .refine((value) => !value || /^d{4}-d{2}-d{2}$/.test(value), {
      message: "Application Deadline must be a valid date (YYYY-MM-DD)",
    }),
  resume: z.string().optional(),
  coverLetter: z.string().optional(),
  referral: z.boolean().default(false),
  referralSource: z.string().optional(),
  referralContact: z.string().optional(),
});

export const referralInfo = (form: any) => {
  return (
    <div className="space-y-6 bg-white rounded-lg shadow-sm">
      <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
        <div className="space-y-0.5">
          <FormLabel className="text-base flex items-center">
            <UserPlus className="mr-2 h-5 w-5 text-indigo-500" />
            Referral
          </FormLabel>
          <FormDescription className="text-sm text-gray-500">
            Do you have a referral for this job application?
          </FormDescription>
        </div>
        <Controller
          name="referral"
          control={form.control}
          render={({ field: { onChange, value } }) => (
            <Switch checked={value} onCheckedChange={onChange} />
          )}
        ></Controller>
      </FormItem>

      <FormField
        control={form.control}
        name="referralSource"
        render={({ field }) => (
          <FormItem>
            <FormLabel className="flex items-center text-sm font-medium text-gray-700">
              <LinkedinIcon className="mr-2 h-4 w-4 text-indigo-500" />
              Referral Source
            </FormLabel>
            <FormControl>
              <Input
                placeholder="e.g. LinkedIn, Company Website, Job Fair"
                {...field}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              />
            </FormControl>
            <FormDescription className="text-xs text-gray-500 mt-1">
              Where did you find this referral opportunity?
            </FormDescription>
            <FormMessage className="text-xs text-red-500 mt-1" />
          </FormItem>
        )}
      />

      <FormField
        control={form.control}
        name="referralContact"
        render={({ field }) => (
          <FormItem>
            <FormLabel className="flex items-center text-sm font-medium text-gray-700">
              <User className="mr-2 h-4 w-4 text-indigo-500" />
              Referral Contact
            </FormLabel>
            <FormControl>
              <Input
                placeholder="e.g. John Doe, [email protected]"
                {...field}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
              />
            </FormControl>
            <FormDescription className="text-xs text-gray-500 mt-1">
              Name or contact information of your referral
            </FormDescription>
            <FormMessage className="text-xs text-red-500 mt-1" />
          </FormItem>
        )}
      />
    </div>
  );
};

export const AddApplicationForm = ({ onOpenChange }: { onOpenChange: any }) => {
  const queryClient = useQueryClient();
  const [currentStep, setCurrentStep] = useState(0);
  const { user } = useUser();

  const { data, mutateAsync, isPending } = useMutation({
    mutationFn: (formData: FormData) => createApplication(formData),
    onError: (error) => {
      return alert(error.message || "Failed to update");
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["applications"] });
      onOpenChange(false);
    },
  });

  // 1. Define your form.
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      jobTitle: "",
      companyName: "",
      jobLocation: "",
      jobDescription: "",
      jobType: "part-time",
      applicationDate: "",
      applicationStatus: "applied",
      applicationLink: "",
      applicationNotes: "",
      jobReferenceNumber: "",
      applicationDeadline: "",
      resume: "",
      coverLetter: "",
      referral: false,
      referralSource: "",
      referralContact: "",
    },
  });

  // 2. Define a submit handler.
  async function onSubmit(values: FormValues) {
    const formData: FormData = new FormData();

    const mongoUser = await findUserByClerkId(user?.id);
    formData.append("userId", mongoUser?._id);

    (Object.keys(values) as Array<keyof FormValues>).forEach((key) => {
      const value = values[key];
      if (value !== undefined && value !== null) {
        formData.append(key, value.toString());
      }
    });

    mutateAsync(formData);
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
        {currentStep === 0 && BasicJobInfo(form)}
        {currentStep === 1 && ApplicationDetails(form)}
        {currentStep === 2 && AdditionalInformation(form)}
        {currentStep === 3 && uploads(form)}
        {currentStep === 4 && referralInfo(form)}
        <div className="flex justify-between">
          {currentStep > 0 ? (
            <Button
              type="button"
              onClick={() => setCurrentStep((prev) => prev - 1)}
            >
              Previous
            </Button>
          ) : (
            <div />
          )}
          {currentStep === 4 ? (
            <Button key="submit" type="submit">
              Submit
            </Button>
          ) : (
            <Button
              key="next"
              type="button"
              onClick={() => setCurrentStep((prev) => prev + 1)}
            >
              Next
            </Button>
          )}
        </div>
      </form>
    </Form>
  );
};

Convert Rust (Wasm-Game-Of-Life style app) to single embedded html page

I was following the guide at: https://rustwasm.github.io/book/game-of-life/introduction.html

I had a lot of trouble getting it to work. Much of this had to do with the contents of the www directory not working on an ordinary web server. It needed to be served with npm run start. I read somewhere that I had to do a npm run dist, but I couldn’t find a dist script. npm run build generated the dist directory, but it was missing index.js in addition to some harder-to-solve problems. I eventually got it to work by running npm run start -- --port 4301 --host 0.0.0.0 --disable-host-check on my production server. (see http://dansted.org:4301/ )

However, what I would like to have is a simple single HTML file that I can deploy onto a “dumb” webserver. I found this guide: https://stackoverflow.com/a/51473757/3215004

I pasted my base64 wasm into that code, but loading the resulting HTML file into Firefox gave the following error: Uncaught (in promise) TypeError: import object field './j_game_of_life_bg.js' is not an Object. I think this means that something is hardcoding paths to js files into my WASM.

So, is there a way to stop my WASM depending on external js files? (or otherwise embed all the required pieces into a single HTML file?)

How to reasonable detect key press without modifier key?

What is the most sensible way to detect if a key (e.g. F) is pressed without any modifier key (e.g. Ctrl, Alt, Alt Gr)?

Do you have to explicitly consider every single modifier key?

KeyboardEvent: ctrlKey property, altKey property, AltGraph key value

window.addEventListener("keydown", (event) => {
  if (!event.ctrlKey && !event.altKey && event.key !== "AltGraph" && event.key === "f") {
    doSomething();
  }
});

KeyboardEvent: getModifierState() method

window.addEventListener("keydown", (event) => {
  if (!event.getModifierState("Control") && !event.getModifierState("Alt") && !event.getModifierState("AltGraph") && event.key === "f") {
    doSomething();
  }
});

How to setup cucumber in vue to test the navigation function via BDD

I’m trying to test navigation in a Vue.js application using Cucumber.js. I want to simulate clicking a link on the home page and verify that it navigates to the about page. It seems that this brings up a few problems, such as the Vue tag syntax. Is there a best practice way to solve this problem?

Here is the relevant code:

navigationStep.ts

import { mount } from '@vue/test-utils'
import { Given, When, Then } from '@cucumber/cucumber'
import App from '../../../src/App.vue'
import router from '../../../src/router/index.ts'
import assert from 'assert'

let wrapper

Given('I am at the home page', function () {
  this.wrapper = mount(App, {
    global: {
      plugins: [router]
    }
  })
  router.push('/')
})

When('I click at the link', function () {
  const aboutLink = this.wrapper.get('a[href="/about"]')
  aboutLink.trigger('click')
})

Then('I should be at the second page', function () {
  const currentRoute = router.currentRoute.value.path
  assert.strictEqual(currentRoute, '/about')
})

App.vue

<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <header>
    <img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" />

    <div class="wrapper">
      <HelloWorld msg="You did it!" />

      <nav>
        <RouterLink to="/">Home</RouterLink>
        <RouterLink to="/about">About</RouterLink>
      </nav>
    </div>
  </header>

  <RouterView />
</template>

This is the error message I got:

<script setup lang="ts">


SyntaxError: Unexpected token '<'
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1153:20)
    at Module._compile (node:internal/modules/cjs/loader:1205:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Module.require (node:internal/modules/cjs/loader:1115:19)
    at require (node:internal/modules/helpers:130:18)
    at Object.<anonymous> (C:UsersPatrickSchwendemannDocumentsGitvue-project-basic__tests__bddstepsnavigationStep.ts:3:13)
    at Module._compile (node:internal/modules/cjs/loader:1241:14)
Waiting for the debugger to disconnect...
Waiting for the debugger to disconnect...

Thank you for your help

Turbo: how to re-evaluate some js files after render?

I’m still pretty new to Hotwire. I have this issue, which I think is a common issue with Turbo. I remember I had it before with Turbo-Links, this is because I ended up deactivating it always on my projects.

The problem seems to be that the .js files are not re-evaluated after the Frame is loaded.

These JS have some after-render logic, like the Bootstrap “tooltips”, which requires a query selector to go through all the elements that match and activate the functionality.

I have been searching in Google with no luck:

  • rails turbo reevaluate js
  • rails javascript_include_tag and turbo reload

How can I ask Turbo to reevaluate some of my js files imported with javascript_include_tag like in here?:

<%= javascript_include_tag "phoenix/vendors/dayjs/dayjs.min.js" %>
<%= javascript_include_tag "phoenix/assets/js/phoenix.js" %>

I was expecting something like:

<%= javascript_include_tag "phoenix/assets/js/phoenix.js", turbo_reload: true %>

webhooks of octokit are not working when i am using them through the express server

I have created a webhook handler using the octokit but the webhook server is not when when using it through the express server.
Although the docs of the octokit mention that it supports the web server but for me its returns the response 202

although If instead of express server I create their own server then it start working with response code 200
ex:

const middleware = createNodeMiddleware(app.webhooks, { path });

// This creates a Node.js server that listens for incoming HTTP requests (including webhook payloads from GitHub) on the specified port. When the server receives a request, it executes the `middleware` function that you defined earlier. Once the server is running, it logs messages to the console to indicate that it is listening.
http.createServer(middleware).listen(port, () => {
  console.log(`Server is listening for events at: ${localWebhookUrl}`);
  console.log("Press Ctrl + C to quit.");
});

This doesn’t work when I wrap In express server no console nothing.

import express, { Request, Response } from "express";
import dotenv from "dotenv";
import { createNodeMiddleware } from "@octokit/webhooks";
import fs from "fs";
import { App } from "@octokit/app";
dotenv.config();

const PORT = process.env.PORT || 8000;
const expressApp = express();
const appId = process.env.APP_ID ?? "";
const webhookSecret = process.env.WEBHOOK_SECRET ?? "";
const privateKeyPath = process.env.PRIVATE_KEY_PATH ?? "";

// This reads the contents of your private key file.
const privateKey = fs.readFileSync(privateKeyPath, "utf8");
const octokitApp = new App({
  appId,
  privateKey,
  webhooks: { secret: webhookSecret },
});
expressApp.use(express.json());
const middleware = createNodeMiddleware(octokitApp.webhooks, {
  path: "/api/webhook",
});
expressApp.use(middleware);

octokitApp.webhooks.onAny(() => {
  console.log(`first`);
});
octokitApp.webhooks.on("pull_request.reopened", () => console.log(`first`));

expressApp.get("/", (req: Request, res: Response) => {
  return res.status(200).json({
    message: "Hello world",
  });
});
expressApp.listen(PORT, () => console.log(`Server is running at port ${PORT}`));

toEqual() ignores keys with undefined properties

I have this test:

it("data should NOT match expectation", ()=>{
  const data = {
    prop1: "foo",
    prop2: undefined
  }
  const expectation = {
    prop1: "foo"
  }
  expect(data).not.toEqual(expectation)
})

I am getting this error:

  ● @ExcludeIf() decorator › data should NOT match expectation

    expect(received).not.toEqual(expected) // deep equality

    Expected: not {"prop1": "foo"}
    Received:     {"prop1": "foo", "prop2": undefined}

      32 |       prop1: 'foo',
      33 |     }
    > 34 |     expect(data).not.toEqual(expectation)
         |                      ^
      35 |   })
      36 |   it('Exludes a property from the plainToInstance object', async () => {
      37 |     const data: TestDto = {

It thinks they’re equal when in fact they are not.

What is the solution to this?

Please note that I don’t want to check for type match. I don’t care about it

Understanding behavior of super() in subclassing Object vs. custom wrapper function

Subclassing Object and using super()

class C extends Object {
      constructor(v) {
        super(v);
      }
    }
    
    console.log(new C(1) instanceof Number); // false

Custom Wrapper Function:

function MyObject(v) {
  return new Object(v);
}

class D extends MyObject {
  constructor(v) {
    super(v);
  }
}

console.log(new D(1) instanceof Number); // true

I know MDN docs mention this that in directly subclassing Object it ignores arguments but I’m still not able to understand it fully like why does it do so? What exactly is happening behind the scenes when super(v) is used in a subclass extending Object, and how does it differ from using a wrapper function that explicitly returns an object?

useEffect for popup modal

I am currently trying to incorporate a popup modal function which I have managed to do and works however, I am trying to now create that same function inside a useEffect hook so that it does not re-render every time. So far, I have tried several methods and nothing seems to work. Here is my code:

AppContent.jsx (without useEffect):

import React, { useState, useEffect } from 'react'
import { X } from 'lucide-react'
import { AnimatePresence } from 'framer-motion';
import AppForm from './AppForm';

const AppContent = () => {
    const [ applicationOpen, setApplicationOpen ] = useState(false);
    
    const close = () => setApplicationOpen(false);
    const open = () => setApplicationOpen(true);

  return (
    <>
      <button 
        className='apply-btn'
        onClick={() => applicationOpen ? close() : open()}
      >
        APPLY HERE
      </button>
       
      <AnimatePresence>
        {applicationOpen && <AppForm applicationOpen={applicationOpen} handleClose={close}/>}
      </AnimatePresence>
    </>
  )
}

export default AppContent

The code above works just fine.

AppContent.jsx (with useEffect):

import React, { useState, useEffect } from 'react'
import { X } from 'lucide-react'
import { AnimatePresence } from 'framer-motion';
import AppForm from './AppForm';

const AppContent = () => {
    const [ applicationOpen, setApplicationOpen ] = useState(false);
    
    useEffect(() => {
      const close = () => setApplicationOpen(false);
      const open = () => setApplicationOpen(true);

      close();
      open();
    },[]);

  return (
    <>
      <button 
        className='apply-btn'
        onClick={() => applicationOpen ? close() : open()}
      >
        APPLY HERE
      </button>
       
      <AnimatePresence>
        {applicationOpen && <AppForm applicationOpen={applicationOpen} handleClose={close}/>}
      </AnimatePresence>
    </>
  )
}

export default AppContent

Can someone help me please and point out what I am doing wrong? Thank you.

why my final result doesn’t show in input tag?

$(document).ready(function () {

    let newData = "";
    let num1 = 0;
    let result = 0;
    let operation = null;
    let input = $("div.calc-display input");

    // زمانی که یک عدد کلیک می‌شود
    $(".calc-number-item").click(function () {
        let data = this.innerText;
        newData += data;
        input.val(newData);
    });

    // زمانی که یک عملگر کلیک می‌شود
    $(".calc-operand-item").click(function () {
        num1 = Number(input.val());
        operation = $(this).attr('id');
        input.val("");
        newData = "";
    });

    // زمانی که دکمه مساوی کلیک می‌شود
    $(".equal").click(function () {
        let num2 = Number(input.val());
        if (operation) {
            switch (operation) {
                case 'plus':
                    result = plus(num1,num2);
                    break;
                case 'mines':
                    result = mines(num1,num2);
                    break;
                case 'times':
                    result = times(num1,num2);
                    break;
                case 'devide':
                    result = devide(num1,num2);
                    break;
                default:
                    result = "Error";
            }
            input.val(result);  // نمایش نتیجه در فیلد ورودی
            newData = "";       // ریست کردن newData برای عملیات جدید
            operation = null;   // ریست کردن عملیات برای جلوگیری از مشکلات بعدی
        }
    });

    // توابع ریاضی
    function plus(a,b) {
        return a + b;
    }

    function mines(a,b) {
        return a - b;
    }

    function times(a,b) {
        return a * b;
    }

    function devide(a,b) {
        return a / b;
    }

});

in view of math everything is fine.
but my code doesn’t run correctly.

Unable to get the data schools data using nearby search api

We are using the Location for Places and Nearby search (new) API’sin this screenshot i’m getting only universities not schools and searching for schools in a specific area (Sector 26) of the city of Chandigarh, India. However, the API returns only a few schools while the Google search option on the maps platform of Google, returns more than 15 schools in that area.And in this screenshot all the schools for sec 26

So we are unable to understand that why would the API return so fewer number of schools while the regular Google Map search option is able to yield triple that number? this is screenshot of my code

I want to do that the maps platform of Google, returns more than 15 schools in that area. for my specific location by using radius

How to send an attachment with a form in html using Web3Forms

/Im using Web3Forms and the email sends,but the problem is that the attachment shows up as plain text and doesnt open./

 <form action="https://api.web3forms.com/submit" method="post">
            <input type="hidden" name="access_key" value="261987ac-8575-439e-8b44-14d9896905b8">
            <div class="form-group">
                <label for="firstName">Name <span>(required)</span></label>
                <div class="name-inputs">
                    <input type="text" id="firstName" name="firstName" placeholder="First Name" required>
                    <input type="text" id="lastName" name="lastName" placeholder="Last Name" required>
                </div>
            </div>
            <div class="form-group">
                <label for="email">Email <span>(required)</span></label>
                <input type="email" id="email" name="email" placeholder="Email" required>
            </div>
            <div class="form-group">
                <label for="subject">Something about yourself<span>(required)</span></label>
                <input type="text" id="Description" name="Description" placeholder="Description" required>
            </div>
            <div class="form-group">
                <label for="file">Upload your CV <span>(required)</span></label>
                <input type="file" id="myFile" name="filename">
            </div>
            <button type="submit">Send</button>
        </form>

React JS how to properly set Cookies using custom reactHooks?

I am creating the login functionalities of my website but having trouble with setting the Cookie with the token from my backend. The token is being returned properly and is setting the user in the UserContext, however the part where the token is to be stored in the browser Cookie (such as when viewed in the browser developer options Application tab) it is not showing or being set. I have no idea whether the issue is in the Login.jsx or in the useStorage.js. Here are the current codes:

./src/hooks/useStorage.js

import { useCallback, useEffect, useState } from 'react';
import Cookies from 'js-cookie';

function useLocalStorage(key, defaultValue) {
    return useStorage(key, defaultValue, window.localStorage);
};

function useSessionStorage(key, defaultValue) {
    return useStorage(key, defaultValue, window.sessionStorage);
};

function useCookiesStorage(key, defaultValue, options) {
    return useStorage(key, defaultValue, null, options);
};

function useStorage(key, defaultValue, storageObject, options) {
    const [value, setValue] = useState(() => {
        if (storageObject) {
            const jsonValue = storageObject.getItem(key);
            if (jsonValue != null) return JSON.parse(jsonValue);
        } else {
            const cookieValue = Cookies.get(key);
            if (cookieValue != null) return JSON.parse(cookieValue);
        }

        if (typeof defaultValue === "function") {
            return defaultValue();
        } else {
            return defaultValue;
        }
    });

    useEffect(() => {
        if (value === undefined) {
            if (storageObject) {
                return storageObject.removeItem(key);
            } else {
                return Cookies.remove(key, options);
            }
        }

        const jsonValue = JSON.stringify(value);
        if (storageObject) {
            storageObject.setItem(key, jsonValue);
        } else {
            Cookies.set(key, jsonValue, options);
        }
    }, [key, value, storageObject, options]);

    const remove = useCallback(() => {
        setValue(undefined);
    }, []);

    return [value, setValue, remove];
};

export {
    useLocalStorage,
    useSessionStorage,
    useCookiesStorage
};

./src/pages/Login.jsx

import '../assets/css/login.css';
import { Button, Col, Container, Form, Image, InputGroup, Row, Stack } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useContext, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { GetUser, SignIn } from '../utils/Auth';
import Swal from 'sweetalert2';
import { useCookiesStorage } from '../hooks/useStorage';
import UserContext from '../UserContext';

function Login() {
    const { setUser } = useContext(UserContext);
    const navigate = useNavigate();
    const [uidValue, setUidValue] = useState('');
    const [upassValue, setUpassValue] = useState('');
    const [,setToken] = useCookiesStorage('__Secure-auth.session-token', null, {httpOnly: true, secure: true, sameSite: 'Strict'});

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

        Swal.fire({
            title: 'Logging in',
            didOpen: () => {
                Swal.showLoading();
            },
            text: 'Please wait',
            showConfirmButton: false,
            allowOutsideClick: false
        });
        const response = await SignIn(uidValue, upassValue); // Returns response message and token
        
        if (!response || !response.token) {
            Swal.close();
            Swal.fire({
                title: `${response.message}!`,
                icon: 'error',
                text: 'Try again',
                timer: 2000,
                timerProgressBar: false,
                showConfirmButton: false,
                allowOutsideClick: false
            });
        }
        else {
            setToken(response.token); // Set the Cookie '__Secure-auth.session-token'
            const user = await GetUser(response.token); // returns user details
            
            if (!user || !user._id) {
                Swal.close();
                Swal.fire({
                    title: `${response.message}!`,
                    icon: 'error',
                    text: 'Try again',
                    timer: 2000,
                    timerProgressBar: false,
                    showConfirmButton: false,
                    allowOutsideClick: false
                });
            }
            else {
                Swal.close();
                Swal.fire({
                    title: 'Login successful!',
                    icon: 'success',
                    text: 'Redirecting to dashboard, please wait...',
                    timer: 2000,
                    timerProgressBar: false,
                    showConfirmButton: false,
                    allowOutsideClick: false
                })
                .then((result) => {
                    if (result.dismiss === Swal.DismissReason.timer) {
                        setUidValue('');
                        setUpassValue('');
                        setUser({ // Sets user context with details from fetch request
                            uid: user._id,
                            user: user.username,
                            role: user.role
                        });
                        navigate('/dashboard');
                    }
                });
            }
        }
    };

    return (...rest of code);
};

export default Login;

I hope someone could help me with what I am doing wrong, I am fairly new to React JS and studying through project based learning.

DOMContentLoaded event is not firing code outside it working

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>JavaScript  </title>

    <meta charset="UTF-8" />
  </head>

  <body>
    <div class="App"></div>

    <script src="./index.mjs" type="module"></script>
  </body>
</html>

index.mjs

console.log("Script loaded");   this is priting only

document.addEventListener("DOMContentLoaded", () => {
  console.log("DOM fully loaded and parsed");  //nothig prints inside this event
});

I want code inside DOMContentLoaded to work but its not working at all in simple code. Can someone tell me what I am doing wrong here.