-1

I am trying to access the city attribute using postItem.address.city but its throwing error that city isnt defined

[
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },

above is a sample array of object from the api, here is how i tried to access the data:

 {posts.map((postItem) => (
            <tr key={postItem.id}>
              <td>{postItem.id}</td>
              <td>{postItem.name}</td>
              <td>{postItem.username}</td>
              <td>{postItem.address.city}</td>
              <td>{postItem.email}</td>
              <td>

the others attributes are working well except the city attribute

here is the error:

Posts.js:43 
        
       Uncaught TypeError: Cannot read properties of undefined (reading 'city')
    at Posts.js:43:1
    at Array.map (<anonymous>)
    at Posts (Posts.js:37:1)
    at renderWithHooks (react-dom.development.js:14803:1)
    at updateFunctionComponent (react-dom.development.js:17034:1)
    at beginWork (react-dom.development.js:18610:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237:1)
    at invokeGuardedCallback (react-dom.development.js:292:1)
    at beginWork$1 (react-dom.development.js:23203:1)
  • Can you send through the whole array? Do you know for certain that the `"address"` exists on all of the objects in the `Array`? – Harrison Oct 28 '22 at 15:56
  • I'd imagine address is null or undefined – Liam Oct 28 '22 at 15:57
  • Does this answer your question? [How to avoid 'cannot read property of undefined' errors?](https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors) – Liam Oct 28 '22 at 15:57

1 Answers1

0

The problem seems to be that you have no city in your incoming address. The modern way to handle that is with optional chaining. Rather than this:

<td>{postItem.address.city}</td>

You could try this:

<td>{postItem.address?.city}</td>

But, that would leave you with an undefined message, which isn't nice, so you could do this instead:

<td>{postItem.address?.city || 'Unknown City'}</td>

Which outputs the string Unknown City if the city is undefined.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
  • Thanks, This worked only that i dont know how to post to the api to return the city attr instead of "unknown city". Thanks in advance – Noah ark Oct 30 '22 at 00:47