Search code examples
react-nativeaccess-tokenreact-native-navigationasyncstorage

How to move to login to home by using async storage


i have written code for setItem and getItem using async storage then i stored in to access token.now i want to check if user already login in to home page,then if we remove app from recents.if we open app then directly i has to move to home page.

app.js

import React from 'react';
import { createStackNavigator ,createAppContainer } from 'react-navigation';
import  Homescreen  from './components/Homescreen';
import  Loginscreen  from './components/Loginscreen'
import Forgetpassword from './components/Forgotpassword';


const Navstack = createStackNavigator({
// Home: Homescreen,
// Login:Loginscreen
 Login : { screen : Loginscreen},
 Home : { screen: Homescreen },
 Password :{ screen: Forgetpassword}

 });

 const App = createAppContainer(Navstack);
 export default App;

login.js:

 //storing response in accesstoken

 storeToken(responseData)
  {
 AsyncStorage.setItem(ACCESS_TOKEN, responseData, (err)=> {
 if(err){
        console.log("an error");
        throw err;
      }
      console.log("success");
    }).catch((err)=> {
        console.log("error is: " + err);
    });
  }

home.js:

 async getToken() {
 try {
  let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
  if(!accessToken) {
      this.props.navigation.navigate('Login');
      // console.warn(accessToken);

  } else {
      this.setState({accessToken: accessToken})
      console.warn(accessToken);
  }
} catch(error) {
    console.log("Something went wrong");
    // console.warn("Something went wrong");
    this.props.navigation.navigate('Login');

}
}

Solution

  • Try this

    login.js:

    fetch("YOUR URL", {
              method: 'POST',
              headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                "client_id": client_id, 
                "username": email,      
                "password": pass,
                "grant_type": "password"
              }),
            }).then((response) => response.json())
            .then(async(response) => {
                this.setState({isLoading: false});
                if(response.status == "success"){
                    navigate("Home");
                    await AsyncStorage.setItem('isLogin', 'true');
                }else{
                    alert(JSON.stringify(response))
                }
            })
            .catch((error) => {
                alert(error);
            });
    

    And I am using splash screen before login then add

    splash.js:

    async componentDidMount(){
            const isLogin = await AsyncStorage.getItem('isLogin');
            setTimeout(() => {
                this.setState({ isLoading: false })
                const { navigate } = this.props.navigation;
                if(isLogin != null || isLogin == "true")
                    navigate("Home");
                }else{
                    navigate("Login");
                } 
            },2000);
        }
    

    I could not able to understand your code so i post my code so hope this will help you.