I'm new to React Hooks and using react 16.13.1.
I'm going to implement Auth component which enables to handle logging in.
But it does not seem update the state currentUser properly, even though setCurrentUser is called with response Object.
What is wrong with this code?
import React, { useState, useEffect } from "react";
import { Route, Redirect } from "react-router-dom";
import { checkLoggedIn } from "utils/Api";
export const Auth = (props) => {
const [currentUser, setCurrentUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
console.log(currentUser);
useEffect(() => {
const f = async () => {
setIsLoading(true);
console.log(isLoading);
const res = await checkLoggedIn();
if (!!res) { // ==> true
setCurrentUser(res);
console.log(currentUser); // ==> null!
}
setIsLoading(false);
};
f();
});
if (isLoading) {
return <div>loading</div>;
}
console.log(currentUser); // ==> null!
return !!currentUser ? (
<Route children={props.children} />
) : (
<Redirect to={"/login"} />
);
};