So I have Dashboard
component which should display currentUsers
info.
I keep my currentUser
in global context/state
.
The problem is when Dashboard
component renders FIRST time currentUser
is null
even tho user is actually logged in. Because of that I get null
error at line 14 or if I comment dashboard states the if statement on line 22 will happen and it will redirect me even if user is logged in.
Is there a way to await for isLoggedInFunction
to finish and then do the logic in Dashboard
component?
In App.js
export const CurrentUserContext = React.createContext(null); // Global Context
const [currentUser, setCurrentUser] = useState(null); // Global State
// Setting current user
useEffect(() => {
setCurrentUser(isLoggedIn()).catch(err => console.log(err));
}, []);
// IsLoggedIn Method
export function isLoggedIn() {
return localStorage.getItem('user') === null ?
null :
JSON.parse(localStorage.getItem('user'));
}
<CurrentUserContext.Provider value={{ currentUser, setCurrentUser }}> // Provider
CodePudding user response:
You can set the default value for the user to avoid the first error.
In this case you can change your Dashboard
like this:
/* ... */
const {
currentUser = {
isLoggedIn: false,
firstName: 'first name'
}
} = useContext(CurrentUserContext);
const [firstName, setFirstName] = useState(currentUser.firstName);
/* ... */
if (!currentUser.isLoggedIn) {
return <Redirect to={'/login'}/>;
}
/* ... */
To solve the second problem, you need to check if your localStorage
actually contains the user
field after authorization.
CodePudding user response:
I fixed both problems by doing this.
const [currentUser, setCurrentUser] = useState(null); // Replaced this line with next line
const [currentUser, setCurrentUser] = useState(() => isLoggedIn());
And I removed useeffect since I don't need it anymore.
// Setting current user
useEffect(() => {
setCurrentUser(isLoggedIn()).catch(err => console.log(err));
}, []);