So, I am trying to work on the products page in my management software. What i want is when the user lands on the product page, they are able to see their products then also add products. But my requests are not going through and i am not able to make post request that creates the products. Let me share my code with you.
App.jsx
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import Dashboard from './components/Dashboard';
import Layout from './components/shared/Layout';
import Products from './components/Products';
import ProductForm from './components/ProductForm';
function App() {
return (
<div className="App">
<div className="App">
<Router>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Dashboard />} />
<Route path="/products" element={<Products />} />
<Route path="/add-product" element={<ProductForm />} />
</Route>
<Route path="login" element={<div>This is the login page</div>} />
</Routes>
</Router>
</div>
</div>
);
}
export default App;
Then I also have my ProductForm.jsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
export default function ProductForm({ setProducts }) {
const [formData, setFormData] = useState({
name: '',
description: '',
category: '',
sku: '',
barcode: '',
quantityInStock: '',
unitPrice: '',
costPrice: '',
reorderLevel: '',
supplierId: '',
warehouseLocation: '',
status: '',
imageUrl: '',
});
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:3000/add-product', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (!response.ok) {
throw new Error('Failed to add product');
}
navigate('/products');
} catch (error) {
console.error('Error adding product:', error);
}
};
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
return (
<div className='bg-white px-4 py-6 rounded-sm border border-gray-200 w-full mb-8'>
<h2 className='text-xl mb-4 font-bold'>Add Product</h2>
<form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div>
<label className='block text-gray-700'>Name</label>
<input
type='text'
name='name'
value={formData.name}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
required
/>
</div>
<div>
<label className='block text-gray-700'>Description</label>
<input
type='text'
name='description'
value={formData.description}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Category</label>
<input
type='text'
name='category'
value={formData.category}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>SKU</label>
<input
type='text'
name='sku'
value={formData.sku}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Barcode</label>
<input
type='text'
name='barcode'
value={formData.barcode}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Quantity in Stock</label>
<input
type='number'
name='quantityInStock'
value={formData.quantityInStock}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Unit Price</label>
<input
type='number'
name='unitPrice'
value={formData.unitPrice}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Cost Price</label>
<input
type='number'
name='costPrice'
value={formData.costPrice}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Reorder Level</label>
<input
type='number'
name='reorderLevel'
value={formData.reorderLevel}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Supplier ID</label>
<input
type='number'
name='supplierId'
value={formData.supplierId}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Warehouse Location</label>
<input
type='text'
name='warehouseLocation'
value={formData.warehouseLocation}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Status</label>
<input
type='text'
name='status'
value={formData.status}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div>
<label className='block text-gray-700'>Image URL</label>
<input
type='text'
name='imageUrl'
value={formData.imageUrl}
onChange={handleChange}
className='border rounded w-full py-2 px-3 mt-1 focus:border-blue-500 focus:outline-none'
/>
</div>
<div className='col-span-3'>
<button type='submit' className='bg-blue-500 text-white px-4 py-2 rounded-md col-span-1 mt-4'>
Submit
</button>
</div>
</form>
</div>
);
}
and server.jsx
import express from 'express';
import cors from 'cors';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.use(cors());
// Endpoint to create a new product
app.post('/add-product', async (req, res) => {
const {
name, description, category, sku, barcode,
quantityInStock, unitPrice, costPrice, reorderLevel,
supplierId, warehouseLocation, status, imageUrl
} = req.body;
try {
const newProduct = await prisma.product.create({
data: {
name, description, category, sku, barcode,
quantityInStock, unitPrice, costPrice, reorderLevel,
supplierId, warehouseLocation, status, imageUrl
},
});
res.json({data: newProduct});
console.log('Product created:', newProduct);
res.status(201).json({ data: newProduct }); // Return the created product data
} catch (error) {
console.error('Error creating product:', error);
res.status(500).json({ error: 'Error creating product' });
}
});
// Endpoint to fetch all products
app.get('/products', async (req, res) => {
try {
const products = await prisma.product.findMany();
res.json(products);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Error fetching products' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
please some quick help here