When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code?

I am unsure if I am calling the handleLogin function correctly. Can anyone provide guidance on the proper way to do so?

function LoginForm() {
  const { setAuth } = useContext<any>(AuthContext);
  const [showSnackbar, setShowSnackbar] = useState(false);
  const [field, setField] = useState({ username: "", password: "" });
  

  function fieldHandler(e: any) {
    setField({
      ...field,
      [e.target.name]: e.target.value,
    });
  }

  async function handleLogin(e: any) {
    e.preventDefault();
    try {
      const loginReq = await axios.post(
        "https://spda-api.onrender.com/api/auth/login",
        {
          headers: {
            "Content-Type": "application/json;charset=utf-8",
          },
          username: field.username,
          password: field.password,
        }
      );
      const loginResp = await loginReq.data;
      if (loginReq.status === 200) {
        setAuth(loginResp);
        Cookie.set("token", loginResp.token);
      
        Router.push("/admin/dashboard");
      }
    } catch (error) {
      const err = error as AxiosError;
      console.log(err);
      setShowSnackbar(true);
    }
  }

  return (
    <>
      <section className="h-screen">
        <div className="container px-6 py-12 h-full">
          <div className=" md:w-8/12 lg:w-6/12 mb-12 md:mb-0">
            {showSnackbar && <SnackbarAlert message="Login gagal" />}
          </div>
                    <form>
//here is the input for username and password
                <div className="mb-6">
                                 <button
                  type="button"
                  onClick={handleLogin}
                  className="inline-block px-7 py-3 bg-blue-600 text-white font-medium text-sm leading-snug uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out w-full"
                  data-mdb-ripple="true"
                  data-mdb-ripple-color="light"
                >
                  Sign in
                </button>
              </form>
          
        </div>
      </section>
    </>
  );
}

export default LoginForm;

It seems that my approach to calling the function may be incorrect. Any suggestions or advice would be greatly appreciated. Thank you.

Answer №1

Upon closer examination, all I can perceive is type="button"

           <button
              type="submit"                 
            >
              Sign in
            </button>

By specifying the type as submit, data from the form is transmitted to the form handler. With a type of "button," however, there is no interaction between the form handler and button.

Answer №2

If you are using TypeScript, it is recommended to specify the type for the e parameter in the handleLogin function:

async function handleLogin(e: React.SyntheticEvent) { ... }

Next, include the onSubmit event handler in the form element and change the button type to submit, while removing the onClick event:

<form onSubmit="handleLogin">
  //input fields for username and password go here
  <div className="mb-6">
    <button
      type="submit"
      className="inline-block px-7 py-3 bg-blue-600 text-white font-medium text-sm leading-snug uppercase rounded shadow-md hover:bg-blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out w-full"
      data-mdb-ripple="true"
      data-mdb-ripple-color="light"
    >
      Sign in
    </button>
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stable and persistent popup window that remains at the forefront in a Chrome extension

Currently developing a Google Chrome extension and seeking assistance in creating a popup window that remains fixed in one corner while staying on top of all other windows. Here is a reference image for clarification: https://i.stack.imgur.com/IPw7N.jpg ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Drawing on Canvas with Html5, shifting canvas results in significant issues

I've been working on developing an HTML5 drawing app, and while I have all the functionality sorted out, I'm facing challenges during the design phase. My main issue is centered around trying to make everything look visually appealing. Specifical ...

The Angular directive was unable to reach the controller located higher up in the DOM hierarchy

template <section id="content" ng-controller="ReservationController as resvnCtrl" > <form role="form" name="resvnCtrl.form"> <div data-date-picker> </div> ...

What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project. What is the most efficient way to achieve this with minimal code? Here's what I have attempted: Index.cshtml: v ...

implement a dropdown feature for a vertical menu with the help of Jquery

Struggling to implement a dropdown feature on a vertical navigation using Jquery. The HTML includes a nav section with 1st level list items and nested li's for second level menu items. On clicking the 1st level li, the intention is to toggle SHOW/HID ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

Error: Property 'html' is undefined - AJAX response must be displayed only in a specific div

I encountered an issue: Uncaught TypeError: Cannot read property 'html' of undefined I am working on implementing a voting system for each video on my webpage from a database. I have successfully integrated it using AJAX, but the problem is ...

Exciting Angular feature: Dynamic Titles

I am working with an <i> tag <i class="actionicon icon-star" [ngClass]="{'yellow' : data.isLiked}" (click)="Like(data)" aria-hidden="true" title="Liked"></i> In my current set ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

How can you set the listbox in Sumo Select to always be open?

Is there a way to ensure the listbox is always open by default, as if the user had clicked? ...

Using a Typescript enum as a parameter type can lead to accepting incorrect values

When working with TypeScript, I have defined an enum, and now I want to create a function that accepts a parameter whose value is one of the enum's values. However, TypeScript does not validate the value against the enum, allowing values outside of th ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Linking together or organizing numerous JavaScript function executions in instances where the sequence of actions is crucial

I have implemented a web api method that conducts calculations by using a json object posted to the method. I believe that a jquery post is asynchronous. Assuming this, I want to be able to link multiple calls to the js function invoking this api method in ...

Cypress: Conducting Test with Custom Timezone Setting on Windows

My testing environment was set up to run in UTC time zone. I utilized cy.clock() to initialize a date-time in UTC format, which the Web App will then display as the current browser date-time in UTC. In order to achieve this, I ensured TZ=UTC in my environ ...

Attempting to transfer a property from one page to another using the Link component in NextJS

Currently, I have a page containing six Link elements that are meant to redirect to the same destination but with different props based on which link is clicked. To pass props, this is how I've implemented it: <Link href={{ pathname: '/pro ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...