So I'm trying to make a web application where it fetches data from backend API and displays it into frontend (This works) and also having add to cart functionality. I'm trying to store the requested item into localstorage and using state too, When the user clicks on add to cart it should store the item or objects in their localstorage. When I click add to cart this gets added cartItems [object Object]
(This is not clickable) which is not what I want. I want to store the actual objects in localstorage.
import { Card, Button } from 'react-bootstrap'
import axios from 'axios'
function HomeScreen() {
const [products, setProducts] = useState([])
const [cart, setCart] = useState([])
function handleClick(id) {
const chosen_product = axios.get(`http://localhost:8000/api/products/${id}`)
setCart(cart + {chosen_product})
localStorage.setItem("cartItems", cart)
}
useEffect(() => {
async function getProducts() {
try {
const response = await axios.get('http://localhost:8000/api/products/');
setProducts(response.data);
} catch (error) {
console.error(error);
}
}
getProducts()
},[])
return (
<div>
{products.map(product => (
<Card className="my-3 p-3 rounded" key={product.id}>
<Card.Img src={'http://localhost:8000' + product.image} />
<Card.Body>
<Card.Title as="div">
<strong>{product.name}</strong>
</Card.Title>
<Card.Text as="div">
</Card.Text>
<Card.Text as="h3">
${product.price}
</Card.Text>
<Card.Link>
<Button onClick={()=>handleClick(product.id)} className="btn-primary">Add to cart</Button>
</Card.Link>
</Card.Body>
</Card>
))}
</div>
)
}
export default HomeScreen
See Question&Answers more detail:os