Pocoyo
Pocoyo

Reputation: 65

react-native function is not defined while using firebase

I'm very new to react and react-native world. I have made a new application which uses firebase that has a login screen, user can register with email and password. I wanted to check the user is already registered and redirect to another screen accordingly, as a first step I used constructor and onAuthStateChanged, I wanted to set a state. But I always get function not defined, can anyone please help me.

constructor(props) {
        super(props);

        firebase.initializeApp(FireBaseConfig);

        this.state = {
            currentUser: null,
            emailAddress: '',
            password: '',
            loginError: {
                show: false,
                message: "Unknown error"
            }
        }

        this.saveCurrentUser = this.saveCurrentUser.bind(this);
        this.doLogin = this.doLogin.bind(this);

        firebase.auth().onAuthStateChanged(function (user) {
            saveCurrentUser(user);
        });
    }

    saveCurrentUser(user) {
        this.setState({
            currentUser: user
        });
    }

enter image description here

Thanks

Upvotes: 0

Views: 1070

Answers (1)

enapupe
enapupe

Reputation: 17029

saveCurrentUser is indeed not defined. You can access it under the this keyword, which is a reference to your class. But since you are using a regular function callback on that firebase call, you gotta reference this before.. That's why I added

var saveCurrentUser = this.saveCurrentUser

constructor(props) {
    super(props);

    firebase.initializeApp(FireBaseConfig);

    this.state = {
        currentUser: null,
        emailAddress: '',
        password: '',
        loginError: {
            show: false,
            message: "Unknown error"
        }
    }

    this.saveCurrentUser = this.saveCurrentUser.bind(this);
    this.doLogin = this.doLogin.bind(this);

    var saveCurrentUser = this.saveCurrentUser

    firebase.auth().onAuthStateChanged(function (user) {
        saveCurrentUser(user);
    });
}

saveCurrentUser(user) {
    this.setState({
        currentUser: user
    });
}

You could have used an arrow-function so the var declaration would become unnecessary.

Upvotes: 2

Related Questions