OjayChima
OjayChima

Reputation: 97

Unable to read object property in Javascript

I'm trying to render a page with some details I get from a api call.

useEffect(() =>{
  getCards();
}, [])

  const [userCards, setCards] = useState([])

  const getCards = async (event) => {
  
    let token = localStorage.getItem("user");
  
    await api
      .get("/fetch-card-balance",
      {headers:{"token":`${token}`}})
      
      .then((response) => {
        console.log(response);
        if (response.data.success === false) {
          toast.error(response.data.message);
          setCards(false);
        } else if (response.data.success === true) {
          console.log(response.data.payload)
          setCards(response.data.payload)
        }
      })
      .catch((err) => {
        toast.error(err.response.data.message);
      });
  };
  console.log(userCards)

Here userCards is logged as

[
 {
  balance: 0.00,
  cifNumber: "0001111222",
  createdAt: "2021-08-03T12:19:51.000Z",
  first6: "123456",
  id: 1234,
  last4: "7890"
 },
 {
  balance: 20.00,
  cifNumber: "0002222333",
  createdAt: "2021-07-03T12:19:51.000Z",
  first6: "234567",
  id: 2345,
  last4: "8901"
 }
]

Then I try to use forEach to filter the properties I need

    const cardDetails = []
    userCards.forEach(option =>  cardDetails.push(
     {
      cardNumber: `${option.first6}******${option.last4}`,
      balance: `${option.balance}`
     }
    ))

But when I run

    console.log(cardDetails[0].balance)

I get "Uncaught TypeError: Cannot read property 'balance' of undefined". I've gone over it several times and the only conclusion I have is that I'm missing something that may not be so obvious. Could someone help point out what it is.

Upvotes: 1

Views: 67

Answers (2)

Elis Joaquim
Elis Joaquim

Reputation: 61

Try this out

const cardDetails = userCards.map(function(option) { return {cardNumber: ${option.first6}******${option.last4}, balance: ${option.balance}}});

Upvotes: 0

Jotha
Jotha

Reputation: 428

Using cardDetails[0].balance will only work when there is at least one element in cardDetails. Otherwise getting the first element in the array yields undefined, causing your error message. Since you only fill the array after the API request returns, at least your first render will be done with an empty array.

An easy way to handle this would be checking for if (cardDetails.length > 0) first.

Upvotes: 1

Related Questions