I am building an inventory app that should complete all crud operations. However the update button when clicked will open an empty form (as if I'm adding or posting) instead of a form with the data filled out for a particular item. (Using a sequelize database).
Routes file
const express = require("express");
const router = express.Router();
const { Item } = require("../models");
const { items } = require("../seedData");
// include check, validationResult methods from the Express Validator package in your Express Router
//const { check, validationResult } = require("express-validator");
// GET /items
router.get("/", async (req, res, next) => {
try {
const items = await Item.findAll();
res.send(items);
} catch (error) {
next(error);
}
});
// Get an any individual item
router.get("/:id", async (req, res, next) => {
try {
const item = await Item.findByPk(req.params.id);
if (!item) {
res.status(404);
next();
} else {
res.send(item);
}
} catch (error) {
next(error);
}
});
// POST /api/items
// for when a new additem form is submitted
router.post("/", async (req, res, next) => {
// set defaults
let category = req.body.category?req.body.category:"";
let title = req.body.title?req.body.title:"";
let description = req.body.description?req.body.description:"";
let image = req.body.image?req.body.image:"";
let price = req.body.price?req.body.price:"";
// post the new item to the inventory db
try {
await Item.create({
"category": category,
"title": title,
"description": description,
"image": image,
"price": price
})
res.send("Form submitted successfully.");
} catch (error) {
next(error);
}
});
// DELETE /items/:id
router.delete("/:id", async (req, res, next) => {
try {
await Item.destroy({
where: {
id: req.params.id,
},
});
const items = await Item.findAll();
res.send(items);
} catch (error) {
nexr(error);
}
});
// PUT /items/:id
router.put("/:id", async (req, res, next) => {
try {
const updatedItem = await Item.update(req.body, {
where: { id: req.params.id },
});
const items = await Item.findAll();
res.send(items);
} catch (error) {
next(error);
}
});
module.exports = router;
This is the update component
import React, { useState, useEffect } from 'react';
import { Item } from "./Item";
import apiURL from "../api";
//bootstrap
import "bootstrap/dist/css/bootstrap.min.css";
import Button from "react-bootstrap/Button";
import Form from 'react-bootstrap/Form';
export const Edit = ({setDisplayEdit,setItemDetails, fetchItems}) => {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [price, setPrice] = useState(""); //do i make this a number?
const [category, setCategory] = useState("");
const [image, setImage] = useState("");
const itemsData = {
title,
description,
price,
category,
image,
};
const handleSubmit = async () => {
const response = await fetch(`${apiURL}/items/${item.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(
itemsData // our data TO CREATE here
),
});
const data = await response.json();
setDisplayEdit(false);
setItemDetails(null);
// fetchItems(data);
};
return (
<>
<Form>
<Form.Group className="mb-3" controlId="formBasicEmail">
<Form.Label>Title</Form.Label>
<Form.Control
onChange={(e) => setTitle(e.target.value)}
value={title}
type="text"
placeholder="Item Title"
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Description</Form.Label>
<Form.Control
onChange={(e) => setDescription(e.target.value)}
value={description}
type="text"
placeholder="Description"
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Price</Form.Label>
<Form.Control
onChange={(e) => setPrice(e.target.value)}
value={price}
type="number"
placeholder="Price"
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Category</Form.Label>
<Form.Control
onChange={(e) => setCategory(e.target.value)}
value={category}
type="text"
placeholder="Category"
/>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<Form.Label>Image</Form.Label>
<Form.Control
onChange={(e) => setImage(e.target.value)}
value={image}
type="text"
placeholder="Image"
/>
</Form.Group>
<Button variant="primary" type="submit" onClick={handleSubmit}>
Submit New Item
</Button>
</Form>
</>
);
};
**This is the component that triggers the update component **
import React,{useState} from 'react';
import { Item } from "./Item";
import {Edit} from "./Update"
import apiURL from "../api";
//bootstrap
import "bootstrap/dist/css/bootstrap.min.css";
import Card from "react-bootstrap/Card";
import Button from "react-bootstrap/Button";
import ListGroup from "react-bootstrap/ListGroup";
export const ItemDetails = ({ item, setItemDetails, fetchItems}) => {
const [displayEdit, setDisplayEdit] = useState(false)
//delete handler
const handleDelete = async () => {
try {
const response = await fetch(`${apiURL}/items/${item.id}`, {
method: "DELETE",
});
const data = await response.json();
setItemDetails(null);
} catch (err) {
console.log("An error has occurred!", err);
}
};
// update handler
const handleUpdate = async () => {
try {
const response = await fetch(`${apiURL}/items/${item.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title,
description,
price,
category,
image,
}),
});
const data = await response.json();
setItemDetails({ id: `${item.id}` });
} catch (err) {
console.log("An error has occurred!", err);
}
};
return (
<>
{displayEdit ? (
<Edit setDisplayEdit={setDisplayEdit} setItemDetails={setItemDetails}fetchItems={fetchItems} />
) : (<>
{/* <div className="d-flex justify-content-between "> */}
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src={item.image} />
<Card.Body>
<Card.Title>{item.title}</Card.Title>
<Card.Text>{item.description}</Card.Text>
</Card.Body>
<ListGroup className="list-group-flush">
<ListGroup.Item>{item.category}</ListGroup.Item>
<ListGroup.Item>Price:${item.price}</ListGroup.Item>
</ListGroup>
<Card.Body>
<Button onClick={handleDelete} variant="danger">
Delete
</Button>
<br></br>
<Button variant="success" onClick={()=>setDisplayEdit(true)}>Update</Button>
</Card.Body>
</Card>
<Button variant="primary" onClick={() => setItemDetails(null)}>
Back to All Items
</Button>
</>)}
</>
)
}