Search code examples
react-nativenavigationasyncstoragestack-navigator

'TypeError: Cannot read property 'state' of undefined' error' in react-native


I have created the header using defaultNavigationOptions The navigation bar contains Home, signup, login, create blog options. If the user has signed in then Login option should not be visible, instead, logout option should be enabled. I'm using AsyncStorage to store the token.

App.js:

import React from 'react';
import { CreateBlog } from './app/views/CreateBlog.js';
import { BlogDetails } from './app/views/BlogDetails.js';
import { EditBlog } from './app/views/EditBlog.js';
import { DeleteBlog } from './app/views/DeleteBlog.js';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { Home } from './app/views/Home.js';
import { Login } from './app/views/Login.js';
import {
  StyleSheet, Text, View, TextInput, TouchableHighlight, Alert, AsyncStorage
} from 'react-native';
import { Signup } from './app/views/Signup.js';

const AppNavigator = createStackNavigator(
  {
    CreateBlogRT: {
      screen: CreateBlog
    },
    BlogDetailsRT: {
      screen: BlogDetails
    },
    EditBlogRT: {
      screen: EditBlog
    },
    DeleteBlogRT: {
      screen: DeleteBlog
    },
    SignupRT: {
      screen: Signup
    },
    LoginRT: {
      screen: Login
    },
    HomeRT: {
      screen: Home,
    },
  },
  {
    initialRouteName: 'HomeRT',
      defaultNavigationOptions: ({ navigation }) => ({

      header: <View style={{
        flexDirection: "row",
        height: 80,
        backgroundColor: '#f4511e', fontWeight: 'bold'
      }} >
        <TouchableHighlight onPress={() => navigation.navigate('SignupRT')}>
          <Text > SignUp</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={() => navigation.navigate('CreateChapterRT')}>
          <Text > CreateChapter</Text>
        </TouchableHighlight>
        <TouchableHighlight onPress={() => navigation.navigate('LoginRT')}>
          <Text > Login</Text>
        </TouchableHighlight>
//getting 'TypeError: Cannot read property 'state' of undefined'
        {this.state.logged_in &&

          <TouchableHighlight onPress={async () => {
            await AsyncStorage.removeItem('token');
            await AsyncStorage.removeItem('user_id');
          }}>
            <Text > Logout</Text>
          </TouchableHighlight>
        }
      </View >
    }),
  },


  }
);
const MyRoutes = createAppContainer(AppNavigator);
export default class App extends React.Component {
     constructor(props) {
      super(props);
     this.state = { logged_in: false };
    }
     componentDidMount = async () => {
       var logged_in = await AsyncStorage.getItem('token')
      this.setState({ logged_in: false })

     }

  render() {
    return (
      <MyRoutes />

    );
  }
}

Now on clicking the logout button, it deletes the token. I want the logout button should be visible only if the user has logged in. In the same way login & signup options as well. (

const loggedin=AsyncStorage.getItem('token');if(userloggedin) 
{showlogout:true;showlogin:false;showSignup:false}.

I don't know where to write the code. Thanks in advance.


Solution

  • after sign-in user you can set userloggedin true

    AsyncStorage.setItem('userloggedin',JSON.stringfy(true)
    

    or

    AsyncStorage.setItem('userloggedin',Boolean(true))
    

    then getItem

    const logged-in = AsyncStorage.getItem('userloggedin')
    
    if(loggedin){
    showlogout=true
    showlogin=false
    showSignup=false
    
    or if your are using state
    
    this.setState({
    showlogout:true,
        showlogin:false,
        showSignup:false})
        }.