reactjsmongodbexpressonsubmit

React javascript onSubmit doesn't work, not firing and no message from console.log at frontend


I am a new learner for React.js and I found an article to do the CRUD operations with React Express and mongodb. After implementation of the code, I found there's a problem on adding a user. When I click the 'Save' button, nothing happen. No console.log message neither. I don't know how to debug it. Appreciated if you can help!

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;

Solution

  • The onSubmit is working properly indeed. It may be a CORS problem that causes the server-side code to respond incorrectly.

    To fix the problem, you may add the following statement to the package.json file.

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