TypeError: undefined is not an object (evaluating 'label.toString')

I’m using React Native and I got errors when I use JavaScript functions like this:

const User = ({navigation, route}) => {

  //SIGN OUT
  function signOutHandler() {
    signOut(auth)
    .then(() => {
      console.log('user signed out')
      navigation.navigate('SignIn')
    })
    .catch(err => {
      // console.log(err.message)
    })
  }

  let label = route.params.name
  label.toString().charAt(0).toUppercase();
  console.log(label)

  return (
    <View style={styles.userContainer}>
      <View style={styles.bio}>
        <IconButton name="account-circle" size={70} style={styles.pp} />
        <View style={styles.cred}>
          <Text style={styles.text}>{label}</Text>
          <Text style={styles.text}>{route.params.email}</Text>
          <Text style={styles.text}>You have currently <Text style={styles.bold}>{route.params.notes.length}</Text>  notes.</Text>
        </View>
      </View>
      
      <View style={styles.bc}>
        <Button title='Delete Account' color={'red'} onPress={signOutHandler} />
        <Button title='Sign Out' onPress={signOutHandler} />
      </View>
    </View>
  )
}

export default User

I can’t get the length (with .length()) of an array also. It throws the same error. I think I’m making a simple mistake. I will be glad if you can help me.

>Solution :

If the value of label is undefined it means that route.params.name is not present – name is not a prop on params. You could use optional chaining to prevent an error.

In JavaScript we get the length of arrays using a simple length instead of length() since its a prop not a method.

Leave a Reply