skip to Main Content

I am trying to move the newItems, setNewItems values of [newItems, setNewItems] = useState([]); as props for components used in another web page on the app am building, the Idea is this, while in the new page, I want to loop through the values of newItems array and return a JSX display of a list of items. I am currently not using a database. I would like to know if I am doing it the wrong way, of if it can be done at all. thanks. The error I get is map cannot read the content of newItems. and the contents of newItems displays empty in the console, the error points at the MoneyInOutDetails Component

//MoneyIn Component

const MoneyIn = ({newItems, setNewItems}) => {

 let handleSaveMonyIn = (event) => {
        event.preventDefault(); 
        //setBalanceDue(balanceSet);
        if (totalAmountIn === 0 || itemDescription === "") {
            setSeverity("error")
            //setError(true);
            setMessage("Enter Amount and Item Description");
            setOpen(true)
        } else if (totalSellingPrice > totalAmountIn) {
            console.log(totalSellingPrice);
           // setError(true);
            setSeverity("error")
            setMessage("Total Selling Prices cannot be bigger than Total amount");
            setOpen(true)
        }

        else {
            const newMoneyInData = { totalAmountIn, amountRecieved, balanceDue, newItems, itemDescription };
            setMoneyInData([...moneyInData, newMoneyInData]);

            localStorage.setItem("moneyIn", JSON.stringify(moneyInData));
            document.getElementById("totalAndRecievedAmt").reset();
            document.getElementById("itemDescriptionFrm").reset();
            //setSuccess(true);
            setSeverity("success");
            setMessage("Saved Successfully !!!");
            setOpen(true);
            // setTotalAmountIn(0);
            // setAmountRecieved(0);
            // setBalanceDue(0);
            // setItemDescription('');
             // setNewItems([]);

            
            console.log(newMoneyInData);
        }
      
    }

let handleSaveItem = () => {
        const newItemData = { productName, sellingPriceOfTotal, quantityCount, sellingPrice };
        setNewItems([...newItems, newItemData]);
        console.log(newItemData);
    }
 let handleSaveItemOnclick = () => {
        if (sellingPriceOfTotal > totalAmountIn) {
            console.log(totalAmountIn);
            console.log(sellingPrice);
            console.log("Alert is working");
           // setError(true);
            setSeverity("error")
            setMessage("Selling Price cannot be bigger than Total");
            setOpen(true)

            // setOpen(false)

        } else if (sellingPrice === 0 || productName === "") {
            console.log(sellingPrice);
            console.log(productName);
            setSeverity("error")
            //setError(true);
            setMessage("Product name and Selling price cannot be empty");
            setOpen(true)
        } else {
            handleSaveItem()
            setVisible(!visible)
            setProductName("");
            setSellingPrice(0);
            setQuantityCount(1);
        }
    }

return (
                <div>
                    <div>Items</div>
                    <ItemLists newItems={newItems} handleDelete={handleDelete}/>
                    <div className='totalItemsAdded'>
                        <p>Total</p>
                        <p>${totalSellingPrice}</p>
                    </div>
                </div>
            );
     
}

//ItemList Component

const ItemLists = (props) => {
  
    const newItems = props.newItems;
    const handleDelete =  props.handleDelete;
   
  console.log(newItems);
   
  return (
 

    <div>
        
         {newItems.map((items) => {
                        const { productName, sellingPriceOfTotal, quantityCount, sellingPrice } = items;
                        return (
                            <>
                                <div className='itemsAdded'>
                                    <div className='eachItemAdded'><div>{productName}</div>
                                        <div>{sellingPriceOfTotal} = {sellingPrice} x {quantityCount}</div>
                                    </div>
                                    <div className='deleteEditFont'><FontAwesomeIcon icon={faTrashCan} onClick={() => handleDelete(items)} /></div>

                                </div>

                            </>
                        );
                    })}

    </div>
     

  )
}

export default ItemLists

//App.js Component

const App = () => {
  const [newItems, setNewItems] = useState([]);
 // localStorage.setItem("newIt", JSON.stringify(newItems));

    console.log(newItems);
  return (
    <>
     <Router>
      <Routes>
        <Route path='/' exact element={<Home newItems = {newItems} setNewItems={setNewItems}/>} />
        <Route path='/moneyIn' element={<MoneyIn newItems = {newItems} setNewItems={setNewItems}/>} />
      </Routes>
     </Router>
    </>
  )
}

export default App

//Home Component

const Home = ({newItems, setNewItems}) => {
  return (
    <>
    <div className='allBodyCards'>
   <Balances/>
   <div className='transactions'>
   <DailyTransactions />
   <MoneyInOutDetails newItems={newItems} setNewItems={setNewItems}/>
   </div>
   </div>
   
   </>
  )
}

export default Home

//MoneyInOutDetails Component Where am running the map to list items in JSX

const MoneyInOutDetails = ({newItems, setNewItems}) => {
     console.log(newItems);
    newItems.map((items) => {
        const { productName, sellingPriceOfTotal} = items;
        return (
       <div className='moneyInOutWrapper'>
            <div>{productName}</div>
            <div className='amountAndIcons'>
                <div className='amountInOut'>${sellingPriceOfTotal}</div>
                <div className='deleteEditIcons'>
                    <FontAwesomeIcon icon={faPenToSquare} />
                    <FontAwesomeIcon icon={faTrashCan} />
                </div>
            </div>

        </div>
    ) })
}

export default MoneyInOutDetails

2

Answers


  1. This is not an answer more like a comment
    I don’t have enough reputation to comment
    From the code you supplied, newItems is originally initialized as an empty array. The only place you do set a value to it is in the handleSaveItem() function under the MoneyIn Component
    If you attempt to access newItems before giving it a value in the handleSaveItem, then it would still be empty

    Login or Signup to reply.
  2. Mapping an empty array shouldn’t cause an error in Javascript. I assume that somewhere you are assigning null or undefined to the newItems state. I would start troubleshooting by logging the result of handleSaveItem() before you pass it to setNewItems() and then keep looking for wrong assignments from there.

    As a precaution you can also always map conditionally e.g.

    Array.isArray(newItems) && newItems.map((item) => {
        // ...
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search