'How to display 4 separate React components using Axios call and useState array
I am trying to use an Axios get to get an object that contains all of the information from a single row of a Postgres table that matches the name of a specific book for a "book selling" website. The book name is stored in a localStorage array that is taken from a previous shop page where the user chooses the books they want to buy and the localStorage array of "book names" is then passed into the Axios get in the loop. My problem is within the first Axios get (axios.get(http://localhost:3001/cart/${book})), I believe my code overwrites the component each time and only 1 component is displayed instead of 3 or 4 depending on the number of items that are in the cart. I looked at the React documentation and know I have to use the spread operator but when I tried using it as described in the documentation, it started creating arrays within arrays and broke my page. I know I'm doing something wrong but I'm not familiar enough with React to solve it. Thanks for any help and sorry for the messy code and all the console.log lines, I am still testing!
import React, { useState, useEffect } from "react"; import axios from 'axios'; import '../styles/Cart.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCartShopping, faPlus, faMinus, faTimes } from '@fortawesome/free-solid-svg-icons';
function Cart() {
const [cart, setCart] = useState([]);
let currentcart;
let currentuser;
let cartstatus;
let empty = "empty";
currentcart = JSON.parse(localStorage.getItem("currentCart"));
currentuser = JSON.parse(sessionStorage.getItem('currentUser'));
cartstatus = localStorage.getItem("cartStatus");
let d = new Date();
let date = d.toLocaleString();
console.log(currentcart);
console.log(cartstatus);
const BookItem = ({
book_name,
price,
book_img
}) => (
<div classname='shopInventory'>
<div id='bookCard'>
<img src={book_img} width=
'100%' height='100%'/>
<h3>{book_name}</h3>
${price}
<br/><br/>
<button className="addBtn"><FontAwesomeIcon icon={faPlus}/> Add</button>
<span id='bookQuantity'>0</span>
<button className='minusBtn'><FontAwesomeIcon icon={faMinus} /> Subtract</button>
</div>
</div>
);
useEffect(() => {
currentcart.map((book) =>
axios.get(`http://localhost:3001/cart/${book}`).then((response) => {
const data = response.data
setCart(data)
})
.catch((error) => {
console.log(error)
})
)}, [currentcart.length]);
let orderData ={
username: currentuser,
order: currentcart,
date: date
};
const submitButton = (event) => {
axios.post(`http://localhost:3001/checkout`,orderData).then((response)
=> {
})
.catch((error) => {
console.log(error)
})
}
const clearCart = () => {
cartstatus = localStorage.setItem('cartStatus', empty);
window.location.reload();
}
console.log(cart);
return (
<>
{cartstatus != "empty" ? (
<div>
<div className='cartSection'>
<div>
{cart.map(cart => <BookItem key={cart.book_name} {...cart} />)}
</div>
</div>
<div id='clear-both'></div>
<div id='checkoutBtns'>
<button className='checkoutBtn' onClick={submitButton}><FontAwesomeIcon icon={faCartShopping}/> Checkout</button>
<button className='clearBtn' onClick={clearCart}><FontAwesomeIcon icon={faTimes}/> Clear Cart</button>
</div>
<div id='clear-both'></div>
</div>
) : (
<center>
<h3>
The Cart is empty
</h3>
</center>
)}
</>
); }
export default Cart;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
