user3359964
user3359964

Reputation: 345

'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.

Upvotes: 0

Views: 724

Answers (2)

Waleed Nasir
Waleed Nasir

Reputation: 607

you can use react life-cycle for this work and also use global variable or state , like this

check this image

https://camo.githubusercontent.com/3beddc08b0e4b44fbdcef20809484f9044e091a2/68747470733a2f2f63646e2d696d616765732d312e6d656469756d2e636f6d2f6d61782f323430302f312a736e2d66746f7770305f565652626555414645434d412e706e67

    class Clock 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() {
    const {logged_in} = this.state
        return (
          <div>
            <h1>Hello, world!</h1>
            <h2>It is {logged_in}.</h2>
          </div>
        );
      }
    }

Upvotes: 1

Waleed Nasir
Waleed Nasir

Reputation: 607

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})
    }.

Upvotes: 1

Related Questions