skip to Main Content

I know there is only a slight problem in this code. I’ve been trying to find it but I keep failing, hence I am posting it here. When I manually add data into the useState variables, signin/ signup buttons are working. But when I remove them and try to get values from the form input fields, it passes no data values into the useStates. why’s that?

import React, { useState } from "react";
import styled from "styled-components";
import logo from "../../assets/logo.svg";
import Input from "./Input";

import { Link, useNavigate } from "react-router-dom";
import { colors } from "../../assets/colorPalette";

import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
} from "firebase/auth";
import { doc, setDoc } from "firebase/firestore";
import { db, auth } from "../../config/firebaseConfigs";

const SideBar = ({ formType }) => {
  const [fName, setFName] = useState("laoaso");
  const [lName, setLName] = useState("Rage");
  const [mobile, setMobile] = useState("23456752");
  const [email, setEmail] = useState("[email protected]");
  const [password, setPassword] = useState("123123");
  const [confirmPassword, setConfirmPassword] = useState("123123");

  const navigate = useNavigate();

  const handleChange = (e) => {
    const { name, value } = e.target;
    switch (name) {
      case "fName":
        setFName(value);
        break;
      case "lName":
        setLName(value);
        break;
      case "mobile":
        setMobile(value);
        break;
      case "email":
        setEmail(value);
        break;
      case "password":
        setPassword(value);
        break;
      case "confirmPassword":
        setConfirmPassword(value);
        break;
      default:
        break;
    }
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(
      "Email:",
      email + "nPassword: ",
      password + "nFirst Name: ",
      fName + "nLast Name: ",
      lName + "nMobile: ",
      mobile + "nConfirm Password: ",
      confirmPassword
    );

    // Validate that all required fields are filled
    if (!email || !password) {
      alert("Please fill in all required fields.");
      return;
    }

    if (password !== confirmPassword) {
      console.log("Passwords do not match");
      return;
    }

    try {
      if (formType === "signin") {
        await signInWithEmailAndPassword(auth, email, password);
      } else {
        const userCredential = await createUserWithEmailAndPassword(
          auth,
          email,
          password
        );

        await setDoc(doc(db, "Patients", userCredential.user.email), {
          email,
          fName,
          lName,
          mobile,
          password,
        });
      }
      navigate("/signin");
    } catch (error) {
      alert("Authentication failed" + error.message);
    }
  };
  return (
    <Container>
      <LogoWrapper>
        <img src={logo} alt="CareBridge-Logo" />
        <h3>
          CARE<span> BRIDGE</span>
        </h3>
      </LogoWrapper>
      <Form onSubmit={handleSubmit}>
        <h3>{formType === "signup" ? "Sign Up" : "Sign In"}</h3>
        {formType === "signup" ? (
          <>
            <Input
              id="fName"
              type="text"
              name="fName"
              value={fName}
              placeholder="First Name"
              onChange={handleChange}
            />
            <Input
              id="lName"
              type="text"
              name="lName"
              value={lName}
              placeholder="Last Name"
              onChange={handleChange}
            />
            <Input
              id="Mobile"
              type="tel"
              name="mobile"
              value={mobile}
              placeholder="Phone Number"
              onChange={handleChange}
            />
          </>
        ) : null}
        <Input
          id="email"
          type="email"
          name="email"
          value={email}
          placeholder="Email Address"
          onChange={handleChange}
        />
        <Input
          id="pswd"
          type="text"
          name="password"
          value={password}
          placeholder="Password"
          onChange={handleChange}
        />
        {formType === "signup" ? (
          <Input
            id="confirmpswd"
            type="text"
            name="confirmPassword"
            value={confirmPassword}
            placeholder="Confirm Password"
            onChange={handleChange}
          />
        ) : null}

        <button type="submit">
          {formType === "signup" ? "Sign up" : "Sign in"}
        </button>
      </Form>
      <div>
        <Terms>
          By signing up, I agree to the Privacy Policy <br /> and Terms of
          Service.
        </Terms>
        <h4>
          {formType === "signup" ? (
            <>
              Already have an account?{" "}
              <span>
                <Link to={"/signin"}>Sign in</Link>
              </span>
            </>
          ) : (
            <>
              New to CareBridge?{" "}
              <span>
                <Link to={"/signup"}>Sign up</Link>
              </span>{" "}
              here.
            </>
          )}
        </h4>
      </div>
    </Container>
  );
};

export default SideBar;

I tried changing useState from userData[] to collecting all input fields separately as I have done in the code.

3

Answers


  1. Chosen as BEST ANSWER

    The problem was in an entirely unexpected place. The component I had made using styled components wasn't getting the correct params to receive the id, value, name attributes of the HTML tag. I fixed it btw.

    import React from "react";
    import styled from "styled-components";
    
    const Input = ({ type, placeholder, name, value, onChange }) => {
      return (
        <Container>
          <StyledInput
            placeholder={placeholder && placeholder}
            type={type ? type : "text"}
            required
            autoComplete="off"
            name={name}
            value={value}
            onChange={onChange}
          />
          <Status />
        </Container>
      );
    };
    

  2. I believe it should be "e.target.value" to get the value of the event. Good way of checking in future would be to add a break point to handleChange and check the values of the variable as the break point is hit. Alternately you can use console.log(variable) to output to check the value is as you expect it to be.

    Login or Signup to reply.
  3. You should use callbacks on onChange function something like

    onChange={(e)=> handleChange(e.target)}
    

    then you can use it to set values

    const changeHandler=({name,value})=>{
    // use the values 
    }
    

    one more suggestion you can put all the values on a object and use spread operator to set name and values using set function,
    something like this

      function handleChange({name,value}) {
    setFormData((preFormData) => {
      return { ...preFormData, [name]: value };
    });
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search