Home > Enterprise >  Data mapping react js
Data mapping react js

Time:08-09

Hello so i'm working on a project where i have thru data and displayed i'm having a problem cause the data isn't consistante like for example not all product have sale i want to display the old price and the new one on the product detail page the product having a sale works fine however the ones that doesn't i keep getting " Cannot read properties of undefined (reading 'old_price')" this is the code i'm currently using:

        <div >
        {filters.filter((product) => product.id === id).map((product) => (
          <div className='product-bigger-wrapper'>
          
            <div > 
              <div className="product-detail-container">              
                <div>                    
                  <div className="image-container">
                    <img src={product.image} className="product-detail-image" alt=""/>
                  </div>            
                </div>
                <div className="product-detail-desc">
                  <div className="product-detail-header-title">
                    <h1 className='product-name'>{product.name}</h1>
                  </div>
                  <p className='product-unit-title'> {product.measurement}</p>
                  <div className="product-unit-price-container">
                    
                    <p className='product-unit-price'> ${product.price}</p>
                    { product.sale.old_price !== undefined ?
                      <p className='product-unit-wasprice'> ${product.sale.old_price}</p>
                      : null}


                  </div>              
                  <h4 className='product-description-p'>Product Details: </h4>
                  <div className='description'>
                    <p className='product-description'>{product.description}</p>            
                  </div>          
                </div>
              </div>
          </div>
         
        </div> 
       ))}       
  </div>  

and this is an example of product that has the sale part and product that doesn't enter image description here

CodePudding user response:

The problem is the line where you check for old_price being undefined.

{ product.sale.old_price !== undefined ? <p>...</p> : null }
           ^
           this is undefined in your second product object

You can fix it by checking for the sale object first

{ product.sale && product.sale.old_price !== undefined ? <p>...</p> : null }

or preferably use optional chaining

{ product.sale?.old_price !== undefined ? <p>...</p> : null }

CodePudding user response:

you should first check if stale object exists or not , with help of Optional chaining (?.) in javascript

{ product?.sale?.old_price &&
                  <p className='product-unit-wasprice'> `${product.sale.old_price}`</p>
                  }
  • Related