I am Creating a simple MERN Authentication, my backend works completely fine, and have tested it with postman, it gives boolean responses when checking for if the user is logged in.
Below is the Router to check the logged-in user, and sending the boolean values to the frontend.
router.get("/loggedIn", (req, res) => {
try {
const token = req.cookies.token;
if (!token) return res.json(false);
jwt.verify(token, process.env.JWT_SECRET);
res.send(true);
} catch (err) {
res.json(false);
}
});
In React, I am using Context Hook, to get that response using Axios.
import React, { useState, useEffect, createContext } from "react";
import Axios from "axios";
const AuthContext = createContext();
function AuthContextProvider(props) {
const [loggedIn, setLoggedIn] = useState(undefined);
const getLoggedIn = async () => {
await Axios.get("http://localhost:5000/auth/loggedIn")
.then((res) => setLoggedIn(res.data))
.catch((err) => console.log(err));
};
useEffect(() => {
getLoggedIn();
}, []);
return (
<AuthContext.Provider value={{ loggedIn, getLoggedIn }}>
{props.children}
</AuthContext.Provider>
);
}
export default AuthContext;
export { AuthContextProvider };
I'm using the loggedIn to conditionally render some components, but the value of it or the state always stays false, if I change the state from dev tools conditional rendering works fine.
AuthContext implementation,
const { loggedIn } = useContext(AuthContext);
{loggedIn === false && (
<Link className="nav-link" to="/login">
<FaUser />
</Link>
)}
{loggedIn === true && (
<Link className="nav-link" to="/logout">
<Button variant="outline-dark">Logout</Button>
</Link>
)}
As you can see, I just want to conditionally render a component, but it always returns false
I am new to the ContextHook.