Home > Net >  Why did we set cart props value to empty array? React
Why did we set cart props value to empty array? React

Time:10-15

So I'm following a tutorial. He said we should set cart to empty array in props. As we are checking cart.length===0. And we will get a big fat error, if we do not add it. But i'm not getting any error even if I remove it. I want to know when can I get an error and why would it happen? My cart is getting array of objects from a local file.

Cart Container

// why passing cart = [] instead of cart only
const CartContainer = ({ cart=[], total, dispatch }) => {
  if (cart.length === 0) {
    return (
      <section className="cart">
        {/* cart header */}
        <header>
          <h2>your bag</h2>
          <h4 className="empty-cart">is currently empty</h4>
        </header>
      </section>
    );
  }
  return (
    <section className="cart">
      {/* cart header */}
      <header>
        <h2>your bag</h2>
      </header>
      {/* cart items */}
      <article>
        {cart.map((item) => {
          return <CartItem key={item.id} {...item} />;
        })}
      </article>
      {/* cart footer */}
      <footer>
        <hr />
        <div className="cart-total">
          <h4>
            total <span>${total}</span>
          </h4>
        </div>
        <button
          className="btn clear-btn"
          onClick={() => dispatch({ type: CLEAR })}
        >
          clear cart
        </button>
      </footer>
    </section>
  );
};
const mapStateToProps = (store) => {
  //   return { amount: state.amount };
  const { total, cart } = store;
  return { cart, total };
};

export default connect(mapStateToProps)(CartContainer);

App.js

function App() {
  const initialState = {
      cart: cart,
      total:3,
      amount:7,
  };

  const store = createStore(reducer, initialState);

Reducer

export default function reducer(state, action) {

    if (action.type === CLEAR) {
        return {
            ...state, cart: []
        }
    }
    return state;
}

CodePudding user response:

cart.length WILL throw an error if you're using javascript, it's just, it will throw an error during program runtime that

you can not read property length of undefined

Using typescript you could do

cart?.length

And it would work perfectly fine. To prevent case no.1 you have to assign empty array as default value, so when no props are passes, you indeed have empty array with length of 0 instead of undefined

CodePudding user response:

The reason why you have set an empty array here is because you are expecting the cart to be an array and in case if it is undefined or null it will throw an error. You are not getting an error here is because you have cart = [] in props.

// why passing cart = [] instead of cart only
const CartContainer = ({ cart=[], total, dispatch }) => {

Here you are passing cart = []. This means if if the value of cart is undefined or null then this will take the empty [] as a default value of that prop.

Hence, When you are trying to access cart.length it doesn't throw any error as it is initialized as an empty array [] in params. You will get an error if you do something like this.

const CartContainer = ({ cart, total, dispatch }) => {
if (cart.length === 0) {
    return (
      <section className="cart">
        {/* cart header */}
        <header>
          <h2>your bag</h2>
          <h4 className="empty-cart">is currently empty</h4>
        </header>
      </section>
    );
  }
....

You can handle the error as

...

if (cart?.length === 0) { // In case if optional chaining is not set then try if(cart && cart.length === 0)
    return (
      <section className="cart">
        {/* cart header */}
        <header>
          <h2>your bag</h2>
          <h4 className="empty-cart">is currently empty</h4>
        </header>
      </section>
    );
  }

...
  • Related