skip to Main Content

I’ve thoroughly tested the backend using Postman and it’s responding correctly. However, despite extensive debugging efforts, the frontend isn’t receiving the expected response. I’ve reviewed the code multiple times but can’t identify the issue. Any insights or suggestions would be greatly appreciated.

import { useEffect, useRef, useState } from "react";
import { useNavigate, Link, Form } from "react-router-dom";

import Card from "../Utility/Card";
import "./Authentication.css";
import { validateEmail, validatePassword } from "../Utility/Validator";

const SignupPage = () => {
  const [emailIsValid, setEmailIsValid] = useState(true);
  const [passwordIsValid, setPasswordIsValid] = useState(true);
  const [confirmPasswordIsValid, setConfirmPasswordIsValid] = useState(true);

  const emailInputRef = useRef();
  const passwordInputRef = useRef();
  const confirmPasswordInputRef = useRef();

  useEffect(() => {
    emailInputRef.current.focus();
  }, []);

  // const navigate = useNavigate();

  let isEmail;
  let isPassword;

  const formSubmitHandler = (e) => {
    e.preventDefault();

    const enteredEmail = emailInputRef.current.value;
    const enteredPassword = passwordInputRef.current.value;
    const enteredConfirmPassword = confirmPasswordInputRef.current.value;

    isEmail = validateEmail(enteredEmail);
    isPassword = validatePassword(enteredPassword);

    if (!isEmail) {
      setEmailIsValid(false);
    }

    if (!isPassword) {
      setPasswordIsValid(false);
    }

    if (enteredConfirmPassword !== enteredPassword) {
      setConfirmPasswordIsValid(false);
    }
  };

  const emailChangeHandler = () => {
    setEmailIsValid(true);
  };
  const passwordChangeHandler = () => {
    setPasswordIsValid(true);
  };
  const confirmPasswordChangeHandler = () => {
    setConfirmPasswordIsValid(true);
  };

  return (
    <Card className="form-container">
      <div className="form">
        <h3>Signup</h3>
        <Form method="POST" onSubmit={formSubmitHandler} noValidate>
          <label htmlFor="email">Email</label>
          <input
            type="email"
            id="email"
            name="email"
            ref={emailInputRef}
            onChange={emailChangeHandler}
            style={!emailIsValid ? { border: "1px red solid" } : {}}
          />
          {!emailIsValid && (
            <p className="error-message">Enter a valid email.</p>
          )}
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            name="password"
            ref={passwordInputRef}
            onChange={passwordChangeHandler}
            style={!passwordIsValid ? { border: "1px red solid" } : {}}
          />
          {!passwordIsValid && (
            <p className="error-message">
              Password should be at least 5 characters.
            </p>
          )}
          <label htmlFor="confirmPassword">Confirm Password</label>
          <input
            type="password"
            id="confirmPassword"
            name="confirmPassword"
            ref={confirmPasswordInputRef}
            onChange={confirmPasswordChangeHandler}
            style={!confirmPasswordIsValid ? { border: "1px red solid" } : {}}
          />
          {!confirmPasswordIsValid && (
            <p className="error-message">
              Not matching with the entered password.
            </p>
          )}
          <button type="submit">Submit</button>
          <p>
            Already signed up? <Link to="/auth/login">Login</Link>
          </p>
        </Form>
      </div>
    </Card>
  );
};

export default SignupPage;

export const action = async ({ params, request }) => {
  const data = await request.formData();

  const signupData = {
    email: data.get("email"),
    password: data.get("password"),
    confirmPassword: data.get("confirmPassword"),
  };

  const res = await fetch("http://localhost:8080/auth/signup", {
    method: "POST",
    body: JSON.stringify(signupData),
    headers: {
      "Content-Type": "application/json",
    },
  });

  console.log(res);
};

2

Answers


  1. Chosen as BEST ANSWER

    Found the problem!

    I was doing this:

    The problem was that component automatically submits the form to the action function. But with the onSubmit() event listener it was not doing so.


  2. Unless I’m missing an external package you’re using, formSubmitHandler is responsible for submitting your form fields and sending the API request from your code, so your fetch request should be inside the formSubmitHandler since it’s not calling action() anywhere else.

    Why not just use the form fields and fetch request directly? Like below⬇️

    const formSubmitHandler = async (e) => {
        e.preventDefault();
    
        const enteredEmail = emailInputRef.current.value;
        const enteredPassword = passwordInputRef.current.value;
        const enteredConfirmPassword = confirmPasswordInputRef.current.value;
    
        ...//all previous code
    
       else {
        const signupData = {
           email: enteredEmail,
           password: enteredPassword,
           confirmPassword: enteredConfirmPassword,
        };
    
        const res = await fetch("http://localhost:8080/auth/signup", {
           method: "POST",
           body: JSON.stringify(signupData),
           headers: {
              "Content-Type": "application/json",
           },
        });
    
        console.log(res);      
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search