Please bear in mind, I'm new to ReactJs and have been learning it over the last few months. So I'm learning, please be patient.
I have created two React components, Login
, and Secure
. Login
hosts the FacebookLogin
component found in in this package: https://www.npmjs.com/package/@greatsumini/react-facebook-login
, and I get a successful response from Facebook by the login attempt when the button is pressed. This is supposed to navigate to the Secure
page when successful.
The problem is that I can just navigate directly to the Secure
component in the URL, (I'm using react-router-dom
package for this), but I want any attempt to navigate to a secure page to be redirected to the Login
page.
How can I do this?
Thank you.
CodePudding user response:
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.)
Edit: 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.