Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

499
Visualizações
Why I get "Cannot read properties of undefined (reading 'map')" in React, while there is no syntax error

I'm doing an e-commerce with React and I'm getting an error say

Cannot read properties of undefined (reading 'map')

Which doesn't make sense because I have done the same thing in another component and it works well.

Here is my code below with the comment on the map function that isn't working. Let me if something isn't clear. I've checked the syntax errors and all works fine

    export class CartItem extends Component {

    constructor(props) {
        super(props);
        this.state={
            product: {},
            failedToLoad: false
        }
    }

    async componentWillMount(){
        let data = await this.getProduct(this.props.product.itemId);
        // let product = data.data.product;
        // this.setState({product: product});
        if (data.data.product) {
            this.setState({product: data.data.product});
        } else {
            this.setState({failedToLoad: true});
        }
    }

    async getProduct(id){

        return await fetchTheQuery(
            `query getProduct($id: String!){
                      
                      product(id: $id){
                        name
                         prices{
                          currency
                          amount
                        }
                      }
                    }`, {id: id}
        )
    }

    render() {
        const {addProduct, productsToPurchase} = this.props.cartContext
        const {selectedCurrency} = this.props.currencyContext
        console.log(this.state.product.prices)

        let productFetched = this.state.product

        if (this.state.failedToLoad){
            return (<div>Something went wrong</div>)
        }
        else if (productFetched){

            return(
                <div>
                    <h2> {this.state.product.name} </h2>

                    <h5>
                        {/*There is an error here*/}
                        { this.state.product.prices.map(
                            price =>{
                                if (price.currency == selectedCurrency){
                                    return( <> { getSymbolFromCurrency(selectedCurrency) +" "+ price.amount }</> )
                                }
                            }
                        )}
                    </h5>

                    <button onClick={() => {
                        addProduct(this.props.product.itemId, this.state.product.prices)
                    }}> Add </button>
                    <h4>{productsToPurchase[this.props.itemIndex].qty}</h4>
                    <hr/>
                </div>
            )

        }
        else {
            return <p>Loading............</p>
        }


    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to check if the this.state.product.prices exists in the object. You are getting this error since the collection is empty during the first render.

{ this.state.product.prices 
 && this.state.product.prices.map(
    price =>{
       if (price.currency == selectedCurrency){
           return( 
              <> 
               { 
               getSymbolFromCurrency(selectedCurrency) +" "+ price.amount }.  
               </> )
              }
           }
        )}
             
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda