skip to Main Content

I have made this class:

import React, {Component} from 'react';

import {
    View,
    ActivityIndicator,
    Button
} from 'react-native';

import Auth from '../api/Auth';

export default class LoginScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            alreadyLoggedIn: true
        };
        this.redirectToHome.bind(this);
        this.loginWithFacebook.bind(this);
    }

    componentWillMount() {
        Auth.isAlreadyLoggedIn().then((res) => {
            if(res == true) {
                this.redirectToHome();
            } else {
                this.setState({alreadyLoggedIn: false});
            }
        });
    }

    redirectToHome() {
        this.props.navigator.resetTo({
            screen: 'homeScreen',
            title: 'Meetups'
        });
    }

    loginWithFacebook() {
        Auth.loginWithFacebook().then((success) => {
            if(success == true) {
                this.redirectToHome();
            }
        }).catch((err) => {
            console.error(err);
        });

    }

    render() {
        return(
            <View>
                {this.state.alreadyLoggedIn == false &&
                    <Button title="Login with Facebook" onPress={this.loginWithFacebook} />
                }
                {this.state.alreadyLoggedIn == true &&
                    <ActivityIndicator animating={this.state.alreadyLoggedIn} />
                }
            </View>
        );
    }
 }

Inside the loginWithFacebook function, when it reaches the line where it calls the redirectToHome function, it says this:

_this3.redirectToHome is not a function

enter image description here

Am I accessing this function in a wrong manner? I can’t make the function static and it required the this object.

What should I do?

2

Answers


  1. You need to actually update the ‘member functions’ in the constructor:

    this.redirectToHome = this.redirectToHome.bind(this);
    this.loginWithFacebook = this.loginWithFacebook.bind(this);
    
    Login or Signup to reply.
  2. The problem is that you have done the binding for the functions incorrectly in the constructor.

    constructor(props) {
        super(props);
        this.state = {
            alreadyLoggedIn: true
        };
        this.redirectToHome = this.redirectToHome.bind(this);
        this.loginWithFacebook = this.loginWithFacebook.bind(this);
    }
    

    this.loginWithFacebook.bind(this); will return a new function after proper binding and you then need to use the function returned. Now since you did not assign this newly added function, with this.loginWithFacebook you will be refererring to your own defined function without the binding and hence this.redirectToHome won’t work since this inside it wont refer to the correct context

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search