CodingIsFun33
CodingIsFun33

Reputation: 453

"TypeError: _this2.setState is not a function" React Native

For some reason I am getting the error "TypeError: _this2.setState is not a function"

in my code here:


import React, {useEffect, Component} from 'react';

import {View, Text} from 'react-native';
import firebase from '@react-native-firebase/app';
import auth from '@react-native-firebase/auth';
import firestore from '@react-native-firebase/firestore';

class HomePageContent extends Component {
  state = {
    uData: [],
  };
  componentDidMount() {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        var userID = firebase.auth().currentUser.uid;
        const db = firebase.firestore();

        let userDB = db.collection('Users').doc(userID);
        userDB
          .get()
          .then(doc => {
            if (!doc.exists) {
              console.log('No such document!');
            } else {
              let allUsers = [];
              let data = doc.data();
              let currentUser = data.fName;
              allUsers.push({
                currentUser,
              });
              this.setState({uData: allUsers});
            }
          })
          .catch(err => {
            console.log('Error getting document', err);
          });
      } else {
        // No user is signed in.
      }
    });
  }
  render() {
    return (
      <View style={{alignItems: 'center'}}>
        {this.state.uData.map((value, index) => (
          <Text style={{fontSize: 25}}>Welcome {value.currentUser}</Text>
        ))}
      </View>
    );
  }
}

export default HomePageContent;


Basically I am just trying to set the state and then use it in

  <Text style={{fontSize: 25}}>Welcome {value.currentUser}</Text>

However I am getting the error for some reason. Any ideas why? I am doing it how I would typically do it in reactJS but this is react native.

The full error is this:


Error getting document [TypeError: _this2.setState is not a function. (In '_this2.setState({
                  uData: allUsers
                })', '_this2.setState' is undefined)]

Upvotes: 0

Views: 719

Answers (2)

nipuna-g
nipuna-g

Reputation: 6662

The issue here is that the this context is not the one you are expecting.

When you create a callback method using the function syntax, you are createing a new scope for this. And when you call this.setState JS will be looking for a setState method inside the newly created function.

function(user) {
      ...
      // this refers to the functional context here
}

This can be fixed by using a arrow function.

firebase.auth().onAuthStateChanged((user) => {...}

The arrow function does not have its own binding to the this keyword. You can read a bit more about it here. Since the function doesn't have a this context, it will automatically refer to the parents this which does have the setState method.

Another way to fix this would be to use a function and bind this manually using .bind.

Upvotes: 1

CodingIsFun33
CodingIsFun33

Reputation: 453

Using an arrow function at firebase.auth().onAuthStateChanged((user) => { fixed this thanks @nipuna777

Upvotes: 0

Related Questions