Check User login React Navigation

Asked

Viewed 417 times

-1

In the React Navigation 5 no longer exists the Switch Navigator. In Upgrading Doc the proposed solution to prevent the user from going back to the login screen is this if ternary that checks if the User is logged in.

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        {isLoggedIn ? (
          <>
            <Stack.Screen name="Home" component={HomeScreen} />
            <Stack.Screen name="Settings" component={SettingsScreen} />
          </>
        ) : (
          <Stack.Screen name="SignIn" component={SignInScreen} />
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

But of course I need to create that function isLoggedIn but I have no idea where to start. Someone has any suggestions?

  • isLoggedIn would be a variable, a boolean for example. Probably in your application you should already store something like this in the localStorage, a token, something like that.

  • It would be something like this: async function isLoggedIn() {&#xA; // buscando o user_id do localStorage&#xA; const user_id = localStorage.getItem('user');&#xA; &#xA; }). ???

  • Then you’d have to return something like return user_id !== null to return a Boolean, I think it would work that way. I usually leave some user information logged in using the Context API, so I just check if the variable in the state is true, so when vc logs in it redirects automatically.

1 answer

0

You need to use React-Redux for this or React-context. When logging into the login screen the server must forward you a token. - Armezene the token in localStorage - create a function that when called it checks if this token is valid, ie you must have an api resource on the back that receives the token and return if it is still valid. If yes, this function returns a true. Usually we forward with the status loading also that would be while the request is being made. So you can put some Skeleton or placeholder showing that the request is in progress. There’s a very good explanation for how to do this in the documentation. Follow the link: insert link description here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.