'use client'
import React, { useState } from 'react';
import Link from 'next/link'; // Not directly used here, but kept for consistency
import Layout from '@/component/Layout'; // Corrected import path (use '@/components/Layout')
import ProductCard from '@/component/ProductCard'; // Corrected import path
import productsData from '@/component/data/produect'; // Corrected import path and file name (should be 'products.json')
import type { Product } from '@/types'; // Import Product type
// Function to generate a random ID (simple implementation for demo purposes)
const generateRandomId = (): number => {
return Math.floor(Math.random() * 1000000); // Generates a random number between 0 and 999999
};
// Dashboard component (renamed from HomePage for clarity based on your export)
const Dashboard: React.FC = () => {
// State to manage the list of products, initialized with data from JSON
const [products, setProducts] = useState<Product[]>(productsData);
const [newProduct, setNewProduct] = useState({
id: 0, // Temporary ID, will be overwritten with random ID
name: '',
price: 0,
image: '',
description: '',
});
// Handle input changes for the new product form
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setNewProduct((prev) => ({
...prev,
[name]: name === 'price' ? parseFloat(value) || 0 : value, // Parse price as a number
}));
};
// Handle form submission to add a new product with a random ID
const handleAddProduct = (e: React.FormEvent) => {
e.preventDefault();
const randomId = generateRandomId(); // Generate a random ID
const newProductWithId: Product = { ...newProduct, id: randomId }; // Add random ID to the new product
setProducts((prevProducts) => [...prevProducts, newProductWithId]); // Add to state
setNewProduct({ id: 0, name: '', price: 0, image: '', description: '' }); // Reset form
};
return (
{/* Section for adding a new product */}
Add New Product
Product Name
Price
Image URL
Description
Add Product
export default Dashboard; // Corrected export name (use Dashboard as per your query)
this code if create produect than
import productsData from '@/component/data/produect'; // Corrected import path and file name (should be 'products.json')
this file data updata and data updata than display custom message dispay and /// this over all process like save data in obj than run one function this time emtpy and retun true and only this function return true than next process
Assistant
Here's a complete solution that addresses your requirements:
Data persistence using a server-side API
Object format handling for product data
Validation function that must return true before proceeding
Now, create the API route to handle data persistence:
ts
// app/api/products/route.ts
import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
const dataFilePath = path.join(process.cwd(), 'data', 'products.json');
// GET route to fetch products
export async function GET() {
try {
const fileData = fs.readFileSync(dataFilePath, 'utf-8');
const products = JSON.parse(fileData);
return NextResponse.json({ products });
} catch (error) {
console.error('Error reading products:', error);
return NextResponse.json(
{ error: 'Failed to load products' },
{ status: 500 }
);
}
}
// POST route to add a product
export async function POST(req: NextRequest) {
try {
const newProduct = await req.json();
const fileData = fs.readFileSync(dataFilePath, 'utf-8');
const products = JSON.parse(fileData);
// Add new product to object
products[newProduct.id] = newProduct;
// Write updated data back to file
fs.writeFileSync(dataFilePath, JSON.stringify(products, null, 2));
return NextResponse.json({
products,
message: 'Product added successfully!'
});
} catch (error) {
console.error('Error adding product:', error);
return NextResponse.json(
{ error: 'Failed to add product' },
{ status: 500 }
);
}
}
And create the data file:
json
// data/products.json
{
"1": {
"id": 1,
"name": "Wireless Earbuds",
"price": 49.99,
"image": "https://picsum.photos/seed/earbuds/200/300",
"description": "High-quality wireless earbuds with noise cancellation and long battery life."
},
"2": {
"id": 2,
"name": "Smartphone Case",
"price": 19.99,
"image": "https://picsum.photos/seed/case/200/300",
"description": "Durable protective case for smartphones with shock absorption."
}
// Add remaining products...
}
Key Features:
Object Format Handling:
Products are stored as an object with ID keys for O(1) lookup
Converted to array with Object.values() for rendering
Data Validation:
validateProduct function ensures all required fields exist
Only proceeds with API call if validation passes
Server-side Data Persistence:
API route handles file reading/writing
Products are stored in a JSON file that persists between sessions
Success/Error Messaging:
Clear feedback after each operation
Different styling for success vs error messages
Loading State:
Disabled button and loading indicator during API calls
Prevents duplicate submissions
Type Safety:
TypeScript types ensure data consistency
Proper type definitions for products
To use this solution:
Create the data file in data/products.json with your product data
Create the API route at app/api/products/route.ts
Replace your current dashboard component with the updated code above
This implementation ensures:
Data is properly validated before saving
Products are stored in an object format for efficient lookup
Users receive feedback after each operation
Data persists between sessions
The UI updates automatically after successful saves
If you need to add more validation rules or modify the success/error handling, you can easily extend the validateProduct function and message display logic.