NasyaAS
NasyaAS

Reputation: 249

How to solve TypeError: Cannot read property 'filter' of undefined

I do not get this error when I am compiling on VSC but when I load the page in my browser this is what I see:

TypeError: Cannot read property 'filter' of undefined

and:

  10 |   product={product}
  11 |   addToCart={props.addToCart}
  12 |   removeFromCart={props.removeFromCart}
> 13 |   cartItem={
     | ^  
  14 |     props.cart.filter(cartItem => cartItem.id === product.id)[0]
  15 |   }
  16 | />

Here is the full function:

function ProductListing(props) {
  return (
    <div className="product-listing">
      {props.products.map(product => (
        <ProductListItem
          product={product}
          addToCart={props.addToCart}
          removeFromCart={props.removeFromCart}
          cartItem={
            props.cart.filter(cartItem => cartItem.id === product.id)[0]
          }
        />
      ))}
    </div>
  );
}

Upvotes: 0

Views: 2850

Answers (1)

Dadsquatch
Dadsquatch

Reputation: 566

Make sure that in the parent you conditionally render the child so it's only rendered when the props.cart is ready.

export class ParentContainer extends Component {

    constructor(){
      super()
      this.state  = {
        cart: []
        isLoading: true
      }
    }

    componentWillMount(){
      // fetch('/some/endpoint')
      // massage your data and then push it to state
      .then(card => {
        this.setState({cart, isLoading: false})
      })
    }

    render() {
      return (
        <Fragment>
          {this.state.isLoading ? ( // evalutate if Data is ready to be passed
            <Fragment />
            ) : (
              <CartInformation cart={this.state.cart} />
            )
          }
        </Fragment>
      )
    }
  }

Upvotes: 1

Related Questions