Skip to content
Advertisement

Objects not getting stored into localstorage. – React JS

So I’m trying to make a web application which fetches products from backend API and displays it and I’m also trying to implement add to cart functionality which works by storing products added to the cart by the user in their local storage When I click add to cart this is what gets added currently cartItems [{}] which is not what I want. I want to store the actual object of the product. Here is my current code:

import React, {useState, useEffect} from 'react'
import { Card, Button } from 'react-bootstrap'
import axios from 'axios'


function HomeScreen() {
    const [products, setProducts] = useState([])
    const [cart, setCart] = useState([])
    const [newCart, addToCart] = useState([])
    async function handleClick(id) {
        const chosen_product = axios.get(`http://localhost:8000/api/products/${id}`)
        const newCart = cart.concat(chosen_product);
        setCart(newCart);
        localStorage.setItem("cartItems", JSON.stringify(newCart));
    }
    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

Advertisement

Answer

axios.get returns a promise that needs to be resolved via await/then,catch

updated handleClick function:-

    async function handleClick(id) {
     try{
        const chosen_product = await axios.get(`http://localhost:8000/api/products/${id}`)
        const newCart = cart.concat(chosen_product);
        setCart(newCart);
        localStorage.setItem("cartItems", JSON.stringify(newCart));
     }
     catch(error){
      // error-handling goes here
     }
   }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement