简体   繁体   中英

How to make request on Axios by ID

i'm coding a MERN delivery app i na basic lvl and need a simple back-end. I'm geting all data from database in front-end part by axios

    const [products, setProducts] = useState([]);
    useEffect(()=>{
    axios.get('api/products')
     .then(res => {
         console.log(res)
         setProducts(res.data)
     })
    .catch(err => {
        console.log(err)
    })

})

also I need to get my product to shoping bucket, but dont understand how to do this. This is code work only in front-ent, but when i get my data from database - this code stop working

 let [cartItems, setCartItems] = useState([])

 const addProduct = (product) => {
 const productExist = cartItems.find(item => item.id === product.id)
 if (productExist) {
    setCartItems(cartItems.map(item => item.id === product.id?
        {...productExist, quantity: productExist.quantity + 1}: item));
 } else {
    setCartItems([...cartItems, {...product, quantity: 1}])
ja }
axios.get(`api/products/${productId}`)
     .then(res => {
         console.log(res)
         setProducts(res.data)
     })
    .catch(err => {
        console.log(err)
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM