skip to Main Content

Description:
I have a website where users can log in and are redirected to the home page upon successful login. On the home page, there’s a profile component in the navbar that allows users to view their profile. However, I’ve noticed that the useEffect hook responsible for loading user data and displaying the profile component is not triggering when the user logs in. As a result, the profile component is not displayed until the page is manually refreshed.

I’ve ensured that all other code is running correctly, and the issue seems to be isolated to the useEffect hook. It’s configured to run on component mount, but it doesn’t execute until the page is refreshed.

What could be causing this behavior, and how can I ensure that the useEffect hook runs properly when the user logs in and is redirected to the home page?

Any insights or suggestions would be greatly appreciated. Thank you!

const [user, setUser] = useState(true)
const [extUser, setExtUser] = useState()
 const [menu, setMenu] = useState(false)
 
 
 console.log("Component is rendering"); // seeing output on a console



    useEffect(() => {
        console.log("useEffect is getting mounted");
        const getUser = localStorage.getItem("user_token");
        console.log("Token from localStorage:", getUser); // Log retrieved token

        if (getUser) {
            setUser(true);
            let decodedToken = jwtDecode(getUser);
            let somevar = JSON.parse(JSON.stringify(decodedToken));
            setExtUser(somevar);
            console.log(somevar);
        }
    }, [user]); // tried removing dependency array but work 

{user ? {display the profile here} : (
                                <button
                                    onClick={() => navigate("/auth")}
                                    className="bg-transparent  hover:bg-gray-500 text-black font-bold  hover:text-white py-2 px-4 border border-slate-500 hover:border-transparent rounded-lg">Login</button>
                            )}

2

Answers


  1. Based on your description, it seems the useEffect hook might not be triggering as expected due to the dependency on the user state. When the user logs in and you are setting the user state to true, if it’s already true, then React will not recognize it as a change, and consequently, the useEffect will not rerun.

    Here’s a suggestion to potentially fix the issue:

    Instead of depending on the user state, you could depend on a more specific piece of state that changes when the user logs in, such as the user_token in the local storage.

    useEffect(() => {
        console.log("useEffect is getting mounted");
        const getUserToken = localStorage.getItem("user_token");
        console.log("Token from localStorage:", getUserToken); 
    
        if (getUserToken) {
            setUser(true);
            let decodedToken = jwtDecode(getUserToken);
            let somevar = JSON.parse(JSON.stringify(decodedToken));
            setExtUser(somevar);
        } else {
            setUser(false);
            setExtUser(undefined);
        }
    }, []); 
    
    const loginUser = () => {
        localStorage.setItem("user_token", userTokenFromServer);
        setUser((prevUser) => !prevUser); 
    };
    
    Login or Signup to reply.
  2. You don’t need both user and extUser because user is more of a derived value of extUser unless you want do something else with it but haven’t shown in the code.

    const [user, setUser] = useState(null)
     
        useEffect(() => {
            console.log("useEffect is getting mounted");
            const userToken = localStorage.getItem("user_token");
            console.log("Token from localStorage:", userToken); // Log retrieved token
    
            if (userToken) {
                const decodedToken = jwtDecode(userToken);
                setUser(JSON.stringify(decodedToken));
            }
        }, []);
    
    {user ? {display the profile here} : (
                                    <button
                                        onClick={() => navigate("/auth")}
                                        className="bg-transparent  hover:bg-gray-500 text-black font-bold  hover:text-white py-2 px-4 border border-slate-500 hover:border-transparent rounded-lg">Login</button>
                                )}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search