I need to use the data coming from useContext to authenticate if the user logged in is Admin or not. But it gives the value "undefined" first and then after a delay of 5 seconds it gives the actual value. But by then, the code breaks because it cannot work with "undefined".
import React, { useContext, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { AuthContext } from '../../context/AuthContext';
const Admin = () => {
const history = useHistory();
const { userData } = useContext(AuthContext);
console.log(userData); // ****** This first gives {token: undefined, user: undefined}
/***************************** Then it gives the actual data after 5-10 seconds delay
* {token: "eyJhbGciOiJIUzI", user: {…}}
token: "eyJhbGciOiJIUzI"
user:
isAdmin: true
__v: 0
_id: "5eea03a736b70722c83a7b63"
*******************************************************************/
// I WANT TO FETCH "isAdmin" // so that I can work on further code
if (!userData.user.isAdmin) {
history.push("/");
};
return <h1>Admin Panel</h1>
};
Do I need to use async/await? Because I tried doing it in a custom async funtion and it was throwing another error that we cannot use useContext in non-react-function.