Home > Net >  React array const is storing false values even when condition is false
React array const is storing false values even when condition is false

Time:09-30

I am working on an app and I am fetching data from redux in following component and while fetching data I am using a condition which says if count>0 then store data (For now there are three hard coded counts present in redux store) otherwise dont store anything in my list const, fairly simple and on length of this list const I am rendring many things in my component but the problem is whenever count<0 condition becomes false but list still stores something like this in my list const:

(3) [false, false, false]
0: false
1: false
2: false
length: 3

and here we can clearly see list is not fetching values from redux obviously because condition didnt met but it is storing some false values and we can also see just because of this length of array became 3 and this length is massing my whole component because as I early mentioned I am rendering some stuff at the bottom of component on the basis of this list array length so someone can please assist why it is storing these false stuff and how I can just force it to store empty array when condition is false thanks:

import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import classes from "./Cart.module.css";

const Cart = () => {
  const navigate = useNavigate();
  const [isFound, setIsFound] = useState(true);
  const orders = useSelector((state) => state.data.DUMMY_DATA);
  const total = useSelector((state) => state.data.products_total);
  const [ordersList, setOrdersList] = useState([]);

  useEffect(() => {
    const list = orders.map(
      (val) =>
        val.product_quantity > 0 && {
          id: val.product_id,
          product_name: val.product_name,
          product_title: val.product_title,
          product_price: val.product_price,
          product_quantity: val.product_quantity,
        }
    );
    console.log(list);
    list.length > 0 && setOrdersList(list);
  }, []);

  useEffect(() => {
    if (ordersList.length > 0) {
      setIsFound(true);
    }
  }, [ordersList]);

  const clickDataHandler = () => {
    // console.log(ordersList);
  };

  return (
    <div className={classes.modal}>
      <div className={classes.root}>
        <span
          className={classes.close}
          onClick={() => navigate("/", { replace: true })}
        >
          &times;
        </span>
        {orders.map(
          (data, key) =>
            data.product_quantity > 0 && (
              <div className={classes.wrapper} key={key}>
                <div className={classes.item}>
                  Item: &emsp;&emsp;{data.product_name}
                </div>
                <div className={classes.amount}>
                  Quantity:&emsp;&emsp; {data.product_quantity}
                </div>
                <div className={classes.price}>
                  Price:&emsp;&emsp; {"$"   data.product_price}
                </div>
              </div>
            )
        )}
        {isFound && (
          <div className={classes.order_button_wrapper}>
            <div className={classes.total}>Total amount:&ensp;{total}</div>
            <button className={classes.order_button} onClick={clickDataHandler}>
              Order
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default Cart;

CodePudding user response:

You are using a short-circuit logic - val.product_quantity > 0 && {...}. As long as the the 1st expression (val.product_quantity > 0) is truthy, we get the 2nd expression ({}) result, but if the 1st is falsy, we get the 1st expression result (false).

In addition, Array.map() transforms each item into something else (it can also stay the same), so the resulting array have the same number of items. In your case, use Array.filter() to remove items that don't conform to the condition:

const list = orders.filter(val => val.product_quantity > 0);

You can also map the filtered list:

const list = orders
  .filter(val => val.product_quantity > 0)
  .map(val => ({ ... }));

       
  • Related