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
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:
},
I don't know if this is the right way to do it. but it works now! haha
Cross check data type of
Error variable
handleSignUp
has a stale closure over theerror
value returned by theuseAuthStore
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: