Home > Net >  In ReactJS i am getting this issue while rendering
In ReactJS i am getting this issue while rendering

Time:11-12

below is the error msg image second one is the api from which i need to show only vendor: store_name but while clicking on update button it shows this error otherwise it remains okay and reloading manually only it works

The first image is about the error im getting and the second one is the API from which I need to show only vendor: store_name but while clicking on the update button it shows this error otherwise it remains okay and reloading manually only it works.

Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'store_address')

 let cart_product_item = this.props.cart_product;
      return (
        {
          cart_product_item && cart_product_item.length > 0  ?  
          cart_product_item[0].vendor.store_address : null
        }
      )
   const mapStateToProps = (state) => {
     return {
       cart_product: state.homepageData.cart,   
  };
};
export default connect(mapStateToProps, {myCart})(Checkout);

CodePudding user response:

The question does not provide all the information required to answer, but here is probably what happens:

  1. You render a component
  2. The component needs data from an API, and the data does not arrive immediately. The component renders before the data arrives.
  3. Your component assumes the data is there immediately during first render, and thus throws an error when trying to access a property of an undefined object.

If the problem is indeed this, it can be overcome in many ways:

  1. Make it appear loading if it does not have the data and when it does, display the data. This can be achieved e.g. by cart_product_item?.[0]?.vendor?.store_address || "Loading" or similar.
  2. Do not render the component (= do not return anything other than e.g. null if the data is not there yet.
  • Related