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

Updating ComboBox Selection in Angular 4

When attempting to populate a combobox with the value from a selected row, only the inputs are loading. This section is part of my page: ` <form class="form-horizontal form-label-left parsleyjs" method="post" data-parsley-priority-enabled="false" n ...

Creating a combination of associative keys and numbers within an array using JavaScript

To summarize, my question starts below: I have simply read a JSON file with the following contents: [{"FirstCategory":"Bath","SecondCategory":"Bath Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""}, ...

Updating the selected value in TomSelect based on an ajax response

I am facing an issue setting a value on TomSelect using ajax response. Normally, I would use the following code on a general dropdown: $('#homebasepeg').val(data.hmb_id).change(); However, when I try to apply this on TomSelect, it doesn't s ...

What is the best way to integrate Socket.IO into an Electron application?

I've been looking to incorporate Socket.IO into my Electron application, but the lack of documentation and examples has made it quite challenging. I would greatly appreciate if someone could provide insights on how multiple clients can communicate thr ...

Successive, Interrelated Delayed Invocations

There are two functions in my code, getStudentById(studentId) and getBookTitleById(bookId), which retrieve data through ajax calls. My ultimate goal is to use Deferreds in the following sequence: Retrieve the Student object, Then fetch the Book Title bas ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

How can we determine if the return value from Object.values is an array or not, since it returns a JavaScript array without the brackets?

In my programming code, I work with two separate JSON files. I iterate through each item in the first file and compare its values with those in the second file. Based on the comparison results, I generate a third JSON file which essentially merges the cont ...

Generating a JSON outcome from a SQL server database

My SQL server has the following table layout: Table ( id int, title varchar(40), start Date(), end Date(), allDay bool, username varchar(40) ); I found some code on this blog to create a JSO ...

Tips for making WebDriver pause until Sencha AJAX request finishes

While testing a page with Selenium WebDriver, I encountered an issue related to the Sencha JavaScript library being used on the underlying page. The problem arises when I input a value into a field and an AJAX call is made to validate that field. If the va ...

Collaborate and pass around SQL connections among different modules

One of my recently developed modules consists of three main functions: Establishing a SQL connection Executing a query Closing the connection This module is called in script.js along with other custom modules responsible for various operations that requi ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

Having difficulty with the useState hook in a material ui functional component that integrates with Firebase

Currently, I am endeavoring to create a sign-up form utilizing a Material UI functional component. Within this form, I am aiming to trigger a signup event by using the "onClick" attribute attached to the sign-up button. My approach involves passing the ema ...

Using JavaScript to invoke Applescript commands

Is it feasible to execute Applescript from JavaScript? I would be grateful if someone could offer a sample code or useful reference link. ...

All constructors at the base level must share a common return type

I am looking to convert my JSX code to TSX. I have a snippet that refactors a method from the react-bootstrap library: import {Panel} from 'react-bootstrap'; class CustomPanel extends Panel { constructor(props, context) { super(props ...

Pixijs is unable to load spritesheets correctly

I am currently facing an issue while trying to load a spritesheet in PixiJS following the instructions provided on Below is the code snippet I am using: PIXI.Loader.shared.add('sheet', require('../assets/spritesheet.json')).load(sprite ...

What is the best way to specify parameter names and types for a TypeScript function that can take either one or two arguments?

Looking to create a function with two different calling options: function visit(url: string, options: Partial<VisitOptions>): void function visit(options: Partial<VisitOptions> & {url:string}): void I'm exploring the most effective w ...

A guide to integrating server-side rendering for Material UI's media queries in NextJs

I'm having trouble following the instructions for implementing Material UI's media queries because they are designed for a basic React application and I am working with NextJs. Specifically, I'm not sure where to place the code provided in t ...

Rendering React Js component occurs just once following a state update

My journey with ReactJS is just beginning, and I'm facing an unusual issue which might be due to my unconventional implementation approach. Previously, everything was working smoothly. However, when I tried to introduce new features, things started g ...

Enhancing the Strength of Password Generator

Example of a Simple Password Generator: function createPassword() { var characters = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOP" + "1234567890" + "@\#\-!$%^&*()_+|~=`{}\[\]:\";& ...

What is the best way to input a dynamic post array in PHP?

Explaining this might be challenging, but I will do my best. I have multiple input posts with custom conditions, which means there can be as many custom conditions as needed. Here is the HTML: <input name="type[]" value="type 1"> <input nam ...