Reputation: 1230
I want to add snippet of code into account-protected pages to ensure that if accessed without a valid token, the user is redirected to login page instead.
Hence, I have create a VerifySignInStatus
function which takes in the component to be shown if authentification is successful as an argument, performs the verification, and if verification fails then displays the login page (i.e., AuthPage
component), or if it succeeds then displays the desired component (passed as parameter to the function).
When verification fails, the code correctly renders AuthPage
, however, when verification passes, the <h1>
component is not displayed and instead an error is thrown into the console saying Uncaught Error: Objects are not valid as a React child (found: object with keys {displayComponent}). If you meant to render a collection of children, use an array instead.
.
VerifySignInStatus Function
export function VerifySignInStatus(displayComponent) {
const { token, removeToken, setToken } = UseToken(); // setToken, token, removeToken
const [hasFetched, setHasFetched] = useState(false);
const [isTokenValid, setIsTokenValid] = useState(false);
const tokenExists = token && token !== "" && token !== undefined;
if (tokenExists) {
ValidateToken(token, setHasFetched, setIsTokenValid);
}
if (tokenExists && !hasFetched) {
return <div>Loading</div>;
}
if (!tokenExists || !isTokenValid) {
return <AuthPage setToken={setToken} />;
}
return displayComponent;
}
Dashboard.js (which I'm trying to access with a valid token)
import { VerifySignInStatus } from "./authentication/authFunctions";
function Dashboard() {
return <VerifySignInStatus displayComponent={<h1>Dashboard</h1>} />;
}
export default Dashboard;
Upvotes: 0
Views: 44
Reputation: 1806
You are passing the complete props object as the variable displayComponent
.
You want to extract it from the props like:
VerifySignInStatus({displayComponent}) {
....
}
Upvotes: 2