How to fetch an array of objects and render it in the component as a normal text using React Hooks?

I want to display some cards information in my app fetching data from an API. Each customer has 1, 2 or 3 different cards, I’m using JWToken for authentication but I have not included it here. So, the API response is not static.

Request: GET "/xx/cards"

Response is an array of objects: 

[
    {
        "cardId": "1",
        "cardType": {
            "3": "General Card" 
        },
        "salutation": {
            "1": "Mrs." 
        },
        "firstName": "Test",
        "lastName": "User",
        "status": 'active',
        "creationDate": "30.10.2020",
        
    },
   {
        "cardId": "2",
        "cardType": {
            "2": "Special Card" 
        },
        "salutation": {
            "2": "Mr." 
        },
        "firstName": "Test1",
        "lastName": "User1",
        "status": 'active',
        "creationDate": "30.10.2020",
        
    },
 
]

In The React Context:

const [cards, setCards] = useState<any>([]);

In MyCards.tsx component:

const MyCards: React.FC = () => {
  const {
    cards,
    setCards,
  } = React.useContext(AuthContext);

  
  const [content, setContent] = useState([]);

  useEffect(() => {
    axios.get("/xx/cards").then(
      (response) => {

        setContent(response.data);
        setCards(response.data);  
      },
      (error) => {
        const _content =
          (error.response && error.response.data) ||
          error.message ||
          error.toString();

        setContent(_content);
      }
    );
  }, []);

  return (
    <React.Fragment>
      <IonPage className="ion-page" id="main-content">
       
       <IonContent className="ion-padding">
          <h1>Your Cards</h1>

          <p>{JSON.stringify(cards)}</p>

        ...HERE I should write some code but don't know what...

        </IonContent>
      </IonPage>
    </React.Fragment>
  );
};

export default MyCards;

I want to list the cards as a normal text (as following) in my component:

Mrs. Test User
Card Id: 1
Card Type: General Card

Mr. Test1 User1
Card Id: 2
Card Type: Special Card

How to achieve this ? I don’t really know how to set state for an array of objects. Any help would be appreciated. Thanks 🙂

Answer

a solution would be to use the map function on your array see here

return(
   ...
    {
     cards.map(card => (
        <p>
          {card.firstName} {card.lastname}<br/>
          Card Id: {card.cardId}<br/>
          ...
        </p>
     ))
    }
   ...
)

like this but for me there is a probleme in api with is all the key number in object ..

better option for iterate is array of object like this :

  [
   {
    "cardId": "1",
    "cardType": "General Card",
    "salutation": "Mrs.",
    "firstName": "Test",
    "lastName": "User",
    "status": 'active',
    "creationDate": "30.10.2020",
   },
   ...

  ]