0

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;
2
  • 1
    should be VerifySignInStatus({displayComponent}) with the {} Commented Jan 25, 2022 at 18:52
  • That solved it indeed, thanks! Sorry if it sounds like a silly question. I'm only few days into React and it's unlike anything I worked with before. Would you like to submit this as an answer? Commented Jan 25, 2022 at 18:55

1 Answer 1

2

You are passing the complete props object as the variable displayComponent.

You want to extract it from the props like:

VerifySignInStatus({displayComponent}) {
....
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.