Using a combination of postgresql database, expressJs, and react, I am currently looking to update a specific column called inCart
within my database. I have implemented a fetch function that utilizes a PUT
method and is triggered by an onClick
event. However, I am unsure how to modify the value in the database once the onClick
event occurs. Below is the code snippet I am currently working with:
import React, { Component, useEffect, useState } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useParams
} from "react-router-dom";
import "./ProductPageBody.scss";
const ProductPageBody = () => {
const [products, setProducts] = useState([]);
let { shirtName } = useParams();
let shirt = products.filter(product => product.name === shirtName);
const [inCart, setInCart] = useState(shirt.inCart);
useEffect(() => {
getProducts();
}, []);
const getProducts = async () => {
try {
const response = await fetch("http://localhost:5000/carts/");
const jsonData = await response.json();
setProducts(jsonData);
} catch (err) {
console.error(err.message);
}
};
//Update inCart Function
const updateInCart = async e => {
e.preventDefault();
try {
{e => setInCart("true")};
const body = { inCart };
const response = await fetch(`http://localhost:5000/carts/${shirt.id}`, {
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
})
console.log(response);
} catch (err)
{
console.error(err.message)
}
}
return (
<div
className="container-fluid mt-5 m-auto p-0"
style={{ paddingTop: "74px" }}
>
{shirt.map((shirt) => (
<div className="row" key={shirt.id}>
<div className="col-md-12 col-lg-4 ml-auto">
<img
src={shirt.image}
alt={shirt.name}
className="img-responsive w-100"
/>
</div>
<div className="col-md-12 col-lg-3 h-25 mt-5 mr-auto">
<h1>{shirt.name}</h1>
<div className="Pricing mt-3 mb-5">
<h3 className="text-danger float-left mr-4">
${shirt.price}
</h3>
<select className="buttons form-control float-left mb-2">
<option>Small</option>
<option>Medium</option>
<option>Large</option>
</select>
<button
type="button"
className="buttons btn btn-danger mt-2 h-auto w-100"
onClick={e => updateInCart(e)}
>
ADD TO CART
</button>
</div>
<p>{shirt.description}</p>
<ul className="mt-2">
<li>{"95% polyester, 5% elastane (fabric composition may vary by 1%)"}</li>
<li>{"95% polyester, 5% elastane (fabric composition may vary by 1%)"}</li>
</ul>
</div>
</div>
))}
</div>
);
};
export default ProductPageBody;
I am making progress but would appreciate any assistance!
Edit: As requested, here is the Express backend code:
const express = require("express");
const app = express();
const cors = require("cors");
const pool = require("./db");
const PORT = 5000;
//
//Middleware
//
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//Listens for server to start
app.listen(PORT, () => {
console.log("Express Server has started on port", { PORT });
});
//
//Routes
//
//Add a product
app.post("/carts", async (req, res) => {
try {
const { name } = req.body;
const { category } = req.body;
const { price } = req.body;
const { description } = req.body;
const { image } = req.body;
const newProduct = await pool.query(
"INSERT INTO products(name, category, price, description, image) VALUES($1, $2, $3, $4, $5) RETURNING *",
[name, category, price, description, image]
);
res.json(newProduct.rows[0]);
} catch (err) {
console.error(err);
}
});
//Show all products
app.get("/carts", async (req, res) => {
try {
const allProducts = await pool.query("SELECT * FROM products");
res.json(allProducts.rows);
} catch (err) {
console.log(err);
}
});
//Show specific product
app.get("/carts/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await pool.query("SELECT * FROM products WHERE id = $1", [
id,
]);
res.json(product.rows[0]);
} catch (err) {
console.log(err);
}
});
//Update a product
app.put("/carts/:id", async (req, res) => {
try {
const { id } = req.params;
const { name } = req.body;
const { category } = req.body;
const { price } = req.body;
const { description } = req.body;
const { image } = req.body;
const { in_cart } = req.body;
const updateProduct = await pool.query(
"UPDATE products SET name = $1, category = $2, price = $3, description = $4, image = $5, in_cart = $6 WHERE id = $7",
[name, category, price, description, image, in_cart, id]
);
res.json("Successfully Updated");
} catch (err) {
console.log(err);
}
});
//Delete a product
app.delete("/carts/:id", async (req, res) => {
try {
const { id } = req.params;
const deleteProduct = await pool.query(
"DELETE FROM products WHERE id = $1",
[id]
);
res.json("Successfully Deleted");
} catch (err) {
console.log(err);
}
});