0

I am trying to make a react native app. I have made the login page but I am not able to solve that how can I make a flag that tells me whether I have a user logged in or not. If the user is logged in go to dashboard. Else login screen.

This is my App.js.

import React, { useState } from 'react';
import { StyleSheet, Text, View, Button, AsyncStorage } from 'react-native';

import Login from './components/Login';
import Dashboard from './components/Dashboard';

export default function App() {
  var [ token, setToken ] = useState('');

  function loginHandler(recievedToken) {
    setToken(recievedToken);
  }
  async function _readData() {
    try {
      const value = await AsyncStorage.getItem('Token');
      console.log(value);
      if (value !== null) {
        // We have data!!
        loginHandler(value)
      } else {
        loginHandler(null);
      }
    } catch (error) {
      // Error retrieving data
    }
  };
  return (
    <View>
      <Login />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31

1 Answers1

0

Ideally, if you're doing a full blown app, you should have an authentication method, and a server, that validates the login, and the session. Most methods use a session token that has an expiry date and is renovated from time to time. This token, and these methods are stored locally on the browser side. An example should be the OAuth algorithm.

On this thread some people discuss ways of storing tokens:

How to store tokens in react native?

Edit: I've written this part about React, not React Native so I'm leaving it below:

You can use session storage to store either that token or just the simplified flag, like you asked.

I'm not qualified to speak of why Session Storage vs Local Storage vs Cookies, and what is the best practice, but here are some links:

https://www.robinwieruch.de/local-storage-react

https://scotch.io/@PratyushB/local-storage-vs-session-storage-vs-cookie

https://oauth.net/2/

Hope this is enough to get you started!