import React, { useEffect, useState, useCallback } from 'react'; import { Container, List, ListItem, ListItemText, TextField, Button, IconButton, Typography, } from '@mui/material'; import { Delete as DeleteIcon, Edit as EditIcon } from '@mui/icons-material'; import axios from 'axios'; import { useParams, useLocation } from 'react-router-dom'; import ItemDetails from './ItemDetails'; // Import the new ItemDetails component export default function Items({ token }) { const { id: boxId } = useParams(); const [items, setItems] = useState([]); const [newItemName, setNewItemName] = useState(''); const [newItemDescription, setNewItemDescription] = useState(''); const [newItemImagePath, setNewItemImagePath] = useState('/images/default.jpg'); const [editingItem, setEditingItem] = useState(null); // Track which item is being edited const location = useLocation(); const boxName = location.state?.boxName || 'Unknown Box'; const fetchItems = useCallback(() => { axios.get(`${process.env.REACT_APP_API_URL}/boxes/${boxId}/items`, { headers: { Authorization: `Bearer ${token}` } }).then(response => { setItems(response.data); }); }, [boxId, token]); useEffect(() => { fetchItems(); }, [boxId, token, fetchItems]); const handleAddItem = () => { axios.post(`${process.env.REACT_APP_API_URL}/items`, { name: newItemName, description: newItemDescription, box_id: parseInt(boxId, 10), }, { headers: { Authorization: `Bearer ${token}` } } ).then(() => { setNewItemName(''); setNewItemDescription(''); setNewItemImagePath(''); fetchItems(); }); }; const handleDeleteItem = (itemId) => { axios.delete(`${process.env.REACT_APP_API_URL}/items/${itemId}`, { headers: { Authorization: `Bearer ${token}` } }).then(() => { fetchItems(); }); }; const handleEditItem = (item) => { setEditingItem(item); // Set the item to be edited }; const handleSaveEdit = () => { setEditingItem(null); // Clear the editing state after saving fetchItems(); // Refresh the list after edit }; return (

Items in Box: {boxName}

{/* Add Item Form */} setNewItemName(e.target.value)} /> setNewItemDescription(e.target.value)} /> setNewItemImagePath(e.target.value)} /> {/* Conditionally render the ItemDetails component if editingItem is not null */} {editingItem ? ( ) : ( {items.map((item) => ( handleEditItem(item)}> handleDeleteItem(item.ID)}> }> {item.description} {item.image_path && ( Image: {item.image_path} )} } /> ))} )}
); }