skip to Main Content
  const handleSubmit = async(e) => {
    e.preventDefault();
    setData({...data, error: null , loading: true})
    if (!first_name || !last_name || !email || !password){
      setData({...data })
    }
    try{
      const result = await createUserWithEmailAndPassword(
        auth,
        email,
        password
      ); 
       await setDoc(doc(db, "users", result.user.uid), {
        uid: result.user.uid ,
        first_name,
        last_name,
        email,
        createdAt: Timestamp.fromDate(new Date()),
        isOnline: true,

      });
      setData({first_name: '',
      last_name: '',
      email: '',
      password: '',
      error: null ,
      loading: false})

      navigate('../', { replace: true })

    } catch (err ){ setData({...data, error: err.message , loading: false})}
  }

this is my code and the problem is in (!first_name || !last_name || !email || !password) what i want is if any of the fields is empty then the form shouldn’t get submitted but even if i leave the first and last name black it still goes through

i don’t know how to fix this

2

Answers


  1. In order to escape the rest of the function you need to return out of it.

    const handleSubmit = async(e) => {
        e.preventDefault();
        setData({...data, error: null , loading: true})
        if (!first_name || !last_name || !email || !password){
          setData({...data });
          return; // <----- this will return out of the function and stop executing the rest of the code within it
        }
        ...
    }
    
    
    Login or Signup to reply.
  2. Adding a return statement within the if block should fix this. This will prevent the execution of the function when the condition is met, preventing subsequent code from running when the required fields are not filled in.

    const handleSubmit = async (e) => {
      e.preventDefault();
      
      // Validate the form fields
      if (!first_name || !last_name || !email || !password) {
        setData({
          ...data,
          error: "All fields are required", 
          loading: false
        });
        return; // Return early to prevent further execution
      }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search