Home > OS >  undefined is not an object (evaluating 'contact.phoneNumbers[0]')
undefined is not an object (evaluating 'contact.phoneNumbers[0]')

Time:09-21

This is my code:

const Contact = ({ contact }) => {
  const [inputValue, setInputValue] = React.useState("");

  const copyText = (text) => {
Clipboard.setString(text);
  };
 return (
<View style={styles.contactCon}>
  <View style={styles.imgCon}>
    <View style={styles.placeholder}>
      <Text style={styles.txt}>{contact?.name[0]}</Text>
    </View>
  </View>
  <View style={styles.contactDat}>
    <Text style={styles.name}>{contact?.name}</Text>
    <Text style={styles.phoneNumber}>
    {contact?.phoneNumbers[0]?.number}
    </Text>
  </View>
</View>
);
};

i realize that the object is not returning the array phoneNumbers as you can see:

Object {
  "contactType": "person",
  "id": "183",
  "imageAvailable": false,
  "lookupKey": "2257i66f1df4389ce4432",
  "name": "null null",
}

I tried to find a solution in the expo documentation, but I didn't find a reason.

Can anyone help me, please

CodePudding user response:

As you have found, contact.phoneNumbers is undefined. Therefore, contact.phoneNumbers[0] is like writing undefined[0].

Obviously you can't access index 0 of undefined, so you get the error that "undefined is not an object".

You need to figure out what you want to display when there is no phone number. Do you want to display "no phone number"? Or an empty string? Or something else?

You can try {contact?.phoneNumbers?.[0]?.number ?? 'No phone number'}.

  • Related