skip to Main Content

I have a simple signup form which works perfectly but I noticed when there is an error it still redirects to the homepage.

import { Loader, Lock, Mail, User } from "lucide-react";
import React, { useState } from "react";
import { motion } from "framer-motion";
import Input from "../components/Input";
import { Link, useNavigate } from "react-router-dom";
import PasswordStrengthMeter from "../components/PasswordStrengthMete";
import { useAuthStore } from "../store/auth.store";

export const SignUpPage = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const { signup, error, isLoading } = useAuthStore();
  const navigate = useNavigate();

  const handleSignUp = async (e) => {
    e.preventDefault();
    try {
      await signup(email, password, name);
     if(!error){
      navigate("/");
     }
    } catch (error) {
      console.log(error);
    }
  };


//authStore.jsx
import { create } from "zustand";

const API_URI = "http://localhost:3001/api/auth";
export const useAuthStore = create((set) => ({
  isLoading: false,
  error: null,
  isAuthenticated: false,
  isCheckingAuth: false,
  message: null,
  user: null,

  signup: async (email, password, name) => {
    set({ isLoading: true, error: null });
    try {
      const options = {
        credentials: "include",
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password, name }),
      };

      const response = await fetch(`${API_URI}/signup`, options);
      console.log(response);

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message);
      }

      const data = await response.json();
      set({ user: data.user, isAuthenticated: true, isLoading: false });
    } catch (error) {
      set({
        error: error.message || "Error signing up",
        isLoading: false,
      });
    }
  },


When I try to go back the browser and hit the button submit it will now prevent it from redirecting because the error is now being stored in the variable. I believe logic is true first before the error variable is stored. that’s why! Is there a better way to do it? or how does the logic work?

3

Answers


  1. Chosen as BEST ANSWER

    I got it Guys, thanks for the help. I added a return value for the signup. The function itself returns 1 and for the catch block return 0 here is the logic:

    //store the return value to reference the redirection logic
     const methodFetch = await signup(email, password, name);
          if (methodFetch === 1) {
            navigate("/verify-email");
          }
    
    
    // authStore.jsx Files
     signup: async (email, password, name) => {
    set({ isLoading: true, error: null });
    try {
       //....logic
    } catch (error) {
      set({
        //....logic
      });
    
      return 0; // return 0 if error
    }
    
    return 1; //success return 1
    

    },

    I don't know if this is the right way to do it. but it works now! haha


  2. Cross check data type of Error variable

    1. String error: "Text"
    if (!error) { 
     // do something
    }
    
    1. Object error: { message: "Text" }
    if (Object.keys(error).length === 0) { 
     // do something
    }
    
    1. Array ( Error: [] or [{status: "Text"}])
    if (Object.keys(error).length === 0) { 
     // do something
    }
    
    Login or Signup to reply.
  3. handleSignUp has a stale closure over the error value returned by the useAuthStore hook.

    I would suggest updating the signup handler to throw errors out for callers to catch and handle. If no errors/exceptions are thrown then assume success, otherwise, catch and handle them appropriately.

    Example:

    signup: async (email, password, name) => {
      set({ isLoading: true, error: null });
      try {
        const options = {
          credentials: "include",
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ email, password, name }),
        };
    
        const response = await fetch(`${API_URI}/signup`, options);
        const data = await response.json();
    
        set({ user: data.user, isAuthenticated: true, isLoading: false });
    
        // Return data to caller
        return data;
      } catch (error) {
        set({
          error: error.message || "Error signing up",
          isLoading: false,
        });
    
        // Re-throw error for caller
        throw error;
      }
    },
    
    const { signup, error, isLoading } = useAuthStore();
    const navigate = useNavigate();
    
    const handleSignUp = async (e) => {
      e.preventDefault();
      try {
        await signup(email, password, name);
        // const data = await signup(email, password, name);
    
        // Success, navigate to home
        navigate("/");
      } catch (error) {
        // Failure, handle error
        console.log(error);
      }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search