简体   繁体   中英

Getting undefined when trying to access properties in array object

I have been stuck for two days trying to access the properties of an array object. I can see in console that the properties exist, but for some reason I can't access them.

I am loading a users contacts when component mounts/useEffect using React-Native, and then I pass them to a function to filter and return only the phoneNumbers.

Here is the async function which load the contacts, setState, and make asynchronous backend calls:

async function getAvailableContacts(contactArray) {
    try {
      const phoneNumbers = filterPhoneNumbers(contactArray);
      const contactsWhoUseApp = await axios.post(
        `${process.env.REACT_APP_backend_url}/available-contacts`,
        { phoneNumbers }
      );
      const newContacts = await getContacts(
        contactArray,
        contactsWhoUseApp.data
      );
      setRenderedContacts((prev) => newContacts);
    } catch (error) {
      console.log(error);
    }
  }

  useEffect(() => {
    (async () => {
      const { status } = await Contacts.requestPermissionsAsync();
      if (status === "granted") {
        const { data } = await Contacts.getContactsAsync({
          fields: [Contacts.Fields.PhoneNumbers],
        });
        if (data.length > 0) {
          setContactArray((prev) => data);
          getAvailableContacts(contactArray);
        }
      }
    })();
  }, []);

This is the function I pass the array to:

export function filterPhoneNumbers(contacts) {
  let arrOfPhoneNumbers = [];
  for (let i = 0; i < contacts.length; i++) {
    console.log(contacts[i].phoneNumbers[0]);
  }
  return arrOfPhoneNumbers;
}

When I console.log contacts[i] this is what I see:

Object {
  "contactType": "person",
  "firstName": "none",
  "id": "123",
  "imageAvailable": false,
  "lastName": "none",
  "lookupKey": "1234567",
  "name": "none none",
  "phoneNumbers": Array [
    Object {
      "id": "12",
      "isPrimary": 1,
      "label": "mobile",
      "number": "+9999999999",
      "type": "2",
    },
    Object {
      "id": "12345",
      "isPrimary": 0,
      "label": "mobile",
      "number": "+9999999999",
      "type": "2",
    },
  ],
}

But I get this error when trying to access phoneNumbers properties:

undefined is not an object (evaluating 'contacts[i].phoneNumbers[0]')

However, when I console.log and remove the [0] from phoneNumbers[0] I can see the phoneNumbers array:

Array [
  Object {
    "id": "123",
    "isPrimary": 1,
    "label": "mobile",
    "number": "+9999999999",
    "type": "2",
  },
  Object {
    "id": "1234",
    "isPrimary": 0,
    "label": "mobile",
    "number": "+9999999999",
    "type": "2",
  },
]

Anyone ever had a similar issue and knows what I am doing wrong?

I can't see how your code is throwing that error, unless you are putting undefined in your contacts array somewhere.

  // Schedule a re-render where contactArray will become data
  setContactArray((prev) => data);
  // Send the OLD contactArray into getAvailableContacts
  // since it hasn't been updated yet
  getAvailableContacts(contactArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM