Reputation: 1762
I have this Component in react which will return 'Loading' title, 'Logged in' title or 'Not Logged in' title, depending on the state.
I have made the state so that it updates and changes from 'Loading' to either 'Logged in' or 'Not Logged in' as soon as the isLoggedIn
promise returns a value of either true
or false
.
However, my second If statment is always conditionally proving false, and hence always returning 'Not Logged in' as a title even if the promise returns true (saying the user is logged in).
Here's the code:
function UserProfileNavItem(props) {
const [profiledLoaded, sethasLoaded] = useState(false);
var isLoggedInLocal = false;
isLoggedIn().then((res) => {
if (res) {
console.log("We are logged in");
isLoggedInLocal = true;
}else{
console.log("We are not logged in");
}
sethasLoaded(true);
});
if (!profiledLoaded) {
return (
<h1>Loading</h1>
);
}
if (!isLoggedInLocal) {
return (
<h1>Not Logged In</h1> // THIS IS ALWAYS SENT BACK EVEN IF isLoggedInLocal IS TRUE
);
} else {
return (
<h1>Logged In</h1> // THIS IS NEVER SENT BACK
);
}
}
Do not think I need to show my isLoggedIn
promise, but ask if you need.
(Yes I am new to react)
Upvotes: 1
Views: 1168
Reputation: 1
Write var isLoggedInLocal = false;
as state in order to be reactive :
function UserProfileNavItem(props) {
const [profiledLoaded, sethasLoaded] = useState(false);
const [isLoggedInLocal , setIsLoggedInLocal ] = useState(false);
isLoggedIn().then((res) => {
if (res) {
console.log("We are logged in");
setIsLoggedInLocal(true);
}else{
console.log("We are not logged in");
}
sethasLoaded(true);
});
if (!profiledLoaded) {
return (
<h1>Loading</h1>
);
}
if (!isLoggedInLocal) {
return (
<h1>Not Logged In</h1> IS TRUE
);
} else {
return (
<h1>Logged In</h1>
);
}
}
Upvotes: 1