The onSubmit function in React JavaScript is failing to execute, it is not triggering and no error message is being displayed on the frontend console

As a newcomer to React.js, I recently came across an article detailing how to perform CRUD operations with React Express and MongoDB. However, after implementing the code, I encountered an issue when trying to add a user. Upon clicking the 'Save' button, nothing happens - no console.log message is displayed either. I am unsure of how to debug this problem and would greatly appreciate any assistance you can provide!

const AddUser = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [gender, setGender] = useState('Male');
  const navigate = useNavigate();

  const saveUser = async (e) => {
    e.preventDefault();
    try {
      await axios.post('http://localhost:5000/users', {
        name,
        email,
        gender,
      });
      navigate('/');
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className='columns mt-5'>
      <div className='column is-half'>
        <form onSubmit={saveUser}>
          <div className='field'>
            <label className='label'>Name</label>
            <div className='control'>
              <input
                type='text'
                className='input'
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder='Name'
              />
            </div>
          </div>
          <div className='field'>
            <label className='label'>Email</label>
            <div className='control'>
              <input
                type='text'
                className='input'
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder='Email'
              />
            </div>
          </div>
          <div className='field'>
            <label className='label'>Gender</label>
            <div className='control'>
              <div className='select is-fullwidth'>
                <select
                  value={gender}
                  onChange={(e) => setGender(e.target.value)}
                >
                  <option value='Male'>Male</option>
                  <option value='Female'>Female</option>
                </select>
              </div>
            </div>
          </div>
          <div className='field'>
            <div className='control'>
              <input type='submit' value='Save' className='button is-success' />
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddUser;

Answer №1

The onSubmit function is functioning correctly as expected. The issue could potentially stem from a CORS (Cross-Origin Resource Sharing) problem, resulting in the server-side code giving an incorrect response.

To resolve this issue, consider including the following statement in the package.json file:

"proxy": "http://localhost:5000",

Answer №2

Once you click the save button, make sure to check the network tab in your browser's development tool to verify the response from this API:

"http://localhost:5000/users"
. In the network tab, scroll to the bottom and locate 'users.' Click on it and then on the right side, there will be another navigation with the response. Click on the Response tab to view it. For a clearer understanding, please refer to this Image1

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

What is the process of incorporating a video into a react.js project through the use of the HTML

I'm experiencing an issue where my video player loads, but the video itself does not. Can anyone shed light on why this might be happening? class App extends Component { render() { return ( <div className="App& ...

Angular's GET HTTP request has resulted in a 500 error message, specifically the Internal Server Error

Attempting to send a GET request to the server where only authenticated users can access a specific route ("/user") after logging in. However, even after a successful login, users are unable to gain access to the "/user" route. A middleware function named ...

Exploring file serving in Node.js with passport authentications

I am currently utilizing Passport with the Google strategy for authentication. Here is my folder structure: views home.html enter.html (this contains just one Google+ button) app.js routes auth.js (handles Google login) I want the client to be direc ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

Tips for resolving the NextJS port already in use issue

My ReactApp is up and running smoothly on port 3000. However, when I decided to launch a new NextJS App for testing purposes, an error popped up: Error: listen EADDRINUSE: address already in use 0.0.0.0:3000 This situation doesn't add up. In a nor ...

Nextjs: Fallback for Loading or Suspense will not be displayed in a production environment

After updating to nextjs v13, I have successfully moved my personal page to the app directory. I experimented with adding loaders for RSCs by first using the fallback prop of the Suspense component and also including a loading component within each route ...

Console displaying a 400 bad request error for an HTTP PUT request

I'm currently in the process of developing a react CRUD application using Strapi as the REST API. Everything is working smoothly with the GET, DELETE, and CREATE requests, but I encounter a 400 bad request error when attempting to make a PUT request. ...

The styled component is not reflecting the specified theme

I have a suspicion that the CSS transition from my Theme is not being applied to a styled component wrapped in another function, but I can't pinpoint the exact reason. I obtained the Basic MUI Dashboard theme from this source and here. Initially, inte ...

The EC2 instance faced a prolonged delay and rejected the connection attempt

Good day to all, I'm seeking assistance with an issue I've been encountering while attempting to host a test project on AWS EC2. Despite following the recommended procedures from tutorials and properly configuring ports and security groups, the ...

Using axios to make a request from a server to itself

I'm facing an issue where I am attempting to send a request from the server to the same server using axios as a PUT method. Here is an example of what I have tried: await axios({ url: `http://localhost:4000${url}`, method: requestType, ...

What is the best way to conceal content within a URL while still transmitting it to the server using node.js and express?

I have been trying to figure out how to hide certain content from the URL, but still need to send that information to the server in my Express app. So far, I haven't found any solutions that work. For example, if I have a URL like www.abc.com/viewblo ...

Executing Firebase Functions offline with secure connections (HTTPS)

I am facing an issue with CORS between my React app served over HTTPS (required for a service worker) and my backend running locally with Firebase Functions. My backend, which is a wrapper for an Express application with the CORS module enabled, is respon ...

Using blending modes with gradient colors in an SVG design

I'm struggling to get my logo to change colors upon scrolling into a button with similar gradient colors, but I just can't seem to make it work. Can anyone lend me a hand? Thank you! Take a look at my Logo. I've attempted to add some styles ...

The error message "Multiple children error occurs when an empty link in Next.js

Is there a way to successfully implement a <Link /> element without any content inside it in my application? Surprisingly, when I don't provide any content, I encounter the multiple children error, even though the opposite seems to be happening. ...

Warning: React has detected that a non-boolean value of `true` was received for the attribute `my-optional-property`

source code import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps extends ButtonProps { "aria-label": string; "my-optional-property"?: boolean; } function MyCustomButton(props: MyButtonProps) { ...

The POST request to the localhost API endpoint resulted in a 404 Not Found error

Whenever I try to send a POST request to "/api/auth/signup" in my JavaScript application, I keep getting a 404 Not Found error. My goal is to create a MERN application for a Modern Real Estate Marketplace. This is the code snippet causing the is ...

Analyzing and refreshing the data entries in firebase database

https://i.stack.imgur.com/ZMjck.png I have been attempting to modify my Username password group name. However, the update process is not successful. I am looking for a way to compare data before updating fields, but I am unable to find a suitable method. ...

Issue with authentication persistence between React frontend and Node.js backend causing passport not to persist user credentials

I have implemented a Node.js and express backend along with a React frontend. Currently, I am using Passport.js with the Local Authentication Strategy. The issue arises when I log in on my React login component; it works perfectly in the Node.js app.post(" ...

How can I ensure that an absolutely positioned element [created with React] snaps to the edge of its parent div when the page loads

I am currently developing a unique two-thumb slider bar component using React. Each thumb in the slider snaps to the closest discrete tick so that users can easily select values along a number line visually. One challenge I'm facing is that the thumbs ...

`Using Google Cloud Endpoints for securing API access`

My current setup involves a GraphQL server using graphql-yoga running on a Node JS express server deployed on Google App Engine. The server exposes an HTTP endpoint with a single route that handles POST requests and returns JSON data to be consumed by a mo ...