I am trying to map this object array but get: Typeerror: Cannot read Property 'map' of Undefined

Asked

Viewed 20 times

-1

import React, { Component } from 'react';
import PurchaseListView from '../purchaseListView'
import './style.scss';

const purchaseData = [{items:[{gtin:'15024', descricao:'sabonete', quantItems: 5, valorUni: 2}, {gtin:'54865', descricao:'saco de arroz', quantItems: 5, valorUni: 15}]}]
    
const ItemsPurchase = props => {
    // const {purchaseData} = props
    return (
        purchaseData.items.map((purchase)=>{
            console.log('purchase')
            console.log(purchase.items)
            return <PurchaseListView gtin={purchase.gtin} descricao={purchase.descricao}/>
        })
    );
}

export default ItemsPurchase;

1 answer

1

It is missing to put the position of array, that is to say, purchaseData is a array and so should be passed as follows:

purchaseData[0].items

Complete code:

const PurchaseListView = ({gtin, descricao}) => {
  return (
    <div>{gtin} - {descricao}</div>
  )
}
    
const ItemsPurchase = props => {
    const purchaseData = [{items:[{gtin:'15024', descricao:'sabonete', quantItems: 5, valorUni: 2}, {gtin:'54865', descricao:'saco de arroz', quantItems: 5, valorUni: 15}]}]
    return (
        purchaseData[0].items.map((purchase)=>{
            return <PurchaseListView gtin={purchase.gtin} descricao={purchase.descricao}/>
        })
    );
}
ReactDOM.render( <ItemsPurchase/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.