skip to Main Content

This is my react code for Protected Route:

import React, { useState } from "react";
import { Navigate, Route } from "react-router-dom";

const ProtectedRoute = (props) => {
  const [isAuthenticated, setisAuthenticated] = useState(false);

    const checkALog = async () => {
        const response = await fetch("http://localhost:3000/checkAuth", {
          credentials: "include",
        });
        const data = await response.json();
        console.log("Response from server:", data); 
        if (data.message === "authenticated") {
          setisAuthenticated(true);
        } else {
          setisAuthenticated(false);
        }
    }
    checkALog();

    console.log(isAuthenticated);

  return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />;
};

export default ProtectedRoute;

I am getting false as the console message when i did console.log(isAuthenticated); . And the backend is properly giving the message in data as "authenticated".

Any suggestions? How can I fix this?

Tried to ask chatgpt but it didn’t help me.

2

Answers


  1. useState doesn’t change the direct value. In react every state is changes when there is any event performed. but there is not event call you have just called you function.
    you could achieve this without useState.

    import React, { useState } from "react";
    import { Navigate, Route } from "react-router-dom";
    
    const ProtectedRoute = (props) => {
        const isAuthenticated = false;
    
        const checkALog = async () => {
            const response = await fetch("http://localhost:3000/checkAuth", {
              credentials: "include",
            });
            isAuthenticated = false;
            const data = await response.json();
            console.log("Response from server:", data); 
            if (data.message === "authenticated") {
              isAuthenticated = true;
            }
        }
        checkALog();
    
        console.log(isAuthenticated);
    
      return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />;
    };
    
    export default ProtectedRoute;
    Login or Signup to reply.
  2. The good practice always is to use useEffect hook whenever you are making any async calls or fetches. Try calling your function checkALog() inside the useEffect hook.

    import React, { useState } from "react";
    import { Navigate, Route } from "react-router-dom";
    
    const ProtectedRoute = (props) => {
        const [isAuthenticated, setisAuthenticated] = useState(false);
    
        const checkALog = async () => {
            const response = await fetch("http://localhost:3000/checkAuth", {
              credentials: "include",
            });
            isAuthenticated = false;
            const data = await response.json();
            console.log("Response from server:", data); 
            if (data.message === "authenticated") {
                setisAuthenticated(true);
            } else {
               setisAuthenticated(false);
            }
        }
    
        useEffect(() => {
            checkALog();
        }, []);
    
        console.log(isAuthenticated);
    
        return isAuthenticated ? <Route {...props} /> : <Navigate to="/" />
    };
    
    export default ProtectedRoute;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search