2

I have created two React components - Login and Secure. Login hosts the FacebookLogin component from this package.

When the button is pressed, it submits the login attempt and I get a successful response from Facebook. Next, the app should navigate to the Secure page, which I do using the react-router-dom package.

However, I found that I can just navigate directly to the Secure component in the URL. How can I make it so that any attempt to navigate to a secure page is redirected to the Login page first?

3
  • 1
    Does this answer your question? Checking authentication in React Commented Nov 26, 2023 at 22:54
  • 2
    Are you this guy? Commented Mar 25, 2024 at 23:53
  • 2
    @CPlus he is I think Commented Oct 20 at 21:50

1 Answer 1

3

According to that component's documentation, you can get the login status in code:

FacebookLoginClient.login((res) => {
  // "res" contains information about the current user's logged-in status
});

So in any component that needs to know the status, simply reference the library:

import { FacebookLoginClient } from '@greatsumini/react-facebook-login';

And use that FacebookLoginClient.login to check the user's logged-in status. If the status doesn't meet the criteria you define, redirect the user. (For example, you can check this in a useEffect when the component first loads, or perhaps on every render if you're paranoid about it.)


For more detail on rendering the target component, since useEffect occurs after the initial render, you can rely on additional state to check. For example, consider this structure:

const [canRender, setCanRender] = useState(false);

useEffect(() => {
  FacebookLoginClient.login((res) => {
    // check the status and call "setCanRender" accordingly
  });
}, []);

if (!canRender) return <>Checking authentication...</>;

// your existing return for the component goes here

The idea here is to default the component to a kind of "loading state" and only render the "secure" content after the authentication has been verified.

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.