Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

javascript - Objects not getting passed into localstorage - React JS

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to store things in localStorage as a string. You also need to wait for the API response, axios.get returns a Promise.

async function handleClick(id) {
  try {
    const chosen_product = await axios.get(`http://localhost:8000/api/products/${id}`)
    setCart(cart + {chosen_product}) // This is wrong, can't add array to object
    localStorage.setItem("cartItems", JSON.stringify(cart)) // This is wrong, cart will still be the previous value
  } catch (err) {
    console.error(err)
  }
}

In fact you already have this code structure in getProducts...

Also this code makes no sense:

setCart(cart + {chosen_product})

You can't add an object to an array.

Also setting cart straight after setCart won't work and cart will still be your previous value at that point, simplest solution is to create a variable for your new state.

const newCart = cart.concat(chosen_product);
setCart(newCart);
localStorage.setItem("cartItems", JSON.stringify(newCart));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...