refactored to use consistent api access via api.js

This commit is contained in:
Steve White 2024-10-30 08:57:41 -05:00
parent bd32bfaae5
commit 165e4965df
6 changed files with 253 additions and 327 deletions

View File

@ -1,8 +1,8 @@
// src/components/Admin.js // src/components/Admin.js
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
import './Admin.css'; // Import the CSS file import './Admin.css'; // Import the CSS file
import { import {
Typography, Typography,
@ -22,120 +22,86 @@ import {
} from '@mui/material'; } from '@mui/material';
export default function Admin() { export default function Admin() {
const [users, setUsers] = useState([]); const [users, setUsers] = useState([]);
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
const [email, setEmail] = useState(''); const [email, setEmail] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const navigate = useNavigate(); const navigate = useNavigate();
const fileInputRef = useRef(null); const fileInputRef = useRef(null);
useEffect(() => {
useEffect(() => {
axios.get(`${process.env.REACT_APP_API_URL}/api/v1/admin/user`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
})
.then(response => {
setUsers(response.data);
})
.catch(error => {
console.error(error);
});
}, []);
const fetchUsers = async () => {
try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/admin/user`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
});
setUsers(response.data);
} catch (error) {
console.error('Error fetching users:', error);
// Optionally, set an error message
// setErrorMessage('Failed to fetch users. Please try again.');
}
};
const handleCreateUser = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/admin/user`, {
username,
password,
email
}, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
});
setUsers([...users, response.data]);
setUsername('');
setPassword('');
setEmail('');
} catch (error) {
console.error(error);
}
};
const handleDeleteUser = async (id) => {
try {
await axios.delete(`${process.env.REACT_APP_API_URL}/api/v1/admin/user/${id}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
});
setUsers(users.filter(user => user.id !== id));
//setUsers(prevUsers => prevUsers.filter(user => user.id !== id));
fetchUsers(); fetchUsers();
}, []);
} catch (error) {
console.error(error);
}
};
const handleBackupDatabase = async () => {
try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/admin/db`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
responseType: 'blob'
});
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'database.db';
a.click();
} catch (error) {
console.error(error);
}
};
const handleRestoreDatabase = async (e) => {
e.preventDefault();
try {
const file = fileInputRef.current.files[0];
const formData = new FormData();
formData.append('database', file);
console.log("sending request to restore db")
const token = localStorage.getItem('token'); const fetchUsers = async () => {
if (!token) { try {
throw new Error('No token found in local storage'); const response = await api.admin.getUsers(localStorage.getItem('token'));
setUsers(response.data);
} catch (error) {
console.error('Error fetching users:', error);
} }
};
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/admin/db`, formData, { const handleCreateUser = async (e) => {
headers: { e.preventDefault();
Authorization: `Bearer ${token}`, try {
'Content-Type': 'multipart/form-data' const response = await api.admin.createUser(localStorage.getItem('token'), {
username,
password,
email
});
setUsers([...users, response.data]);
setUsername('');
setPassword('');
setEmail('');
} catch (error) {
console.error(error);
}
};
const handleDeleteUser = async (id) => {
try {
await api.admin.deleteUser(localStorage.getItem('token'), id);
setUsers(users.filter(user => user.id !== id));
fetchUsers();
} catch (error) {
console.error(error);
}
};
const handleBackupDatabase = async () => {
try {
const response = await api.admin.backupDb(localStorage.getItem('token'));
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'database.db';
a.click();
} catch (error) {
console.error(error);
}
};
const handleRestoreDatabase = async (e) => {
e.preventDefault();
try {
const file = fileInputRef.current.files[0];
const formData = new FormData();
formData.append('database', file);
const response = await api.admin.restoreDb(localStorage.getItem('token'), formData);
if (response.status === 200) {
alert('Database restored successfully');
navigate('/admin');
} }
}); } catch (error) {
console.error(error);
if (response.status === 200) {
alert('Database restored successfully');
navigate('/admin');
} else {
throw new Error(`Failed to restore database: ${response.statusText}`);
} }
} catch (error) { };
console.error(error);
}
};
return ( return (
<Container maxWidth="md"> <Container maxWidth="md">

View File

@ -3,50 +3,43 @@ import React, { useEffect, useState } from 'react';
import { Container, Button, TextField, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material'; import { Container, Button, TextField, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
import { Delete as DeleteIcon } from '@mui/icons-material'; import { Delete as DeleteIcon } from '@mui/icons-material';
import { Link as RouterLink } from 'react-router-dom'; // Import Link from react-router-dom import { Link as RouterLink } from 'react-router-dom'; // Import Link from react-router-dom
import axios from 'axios';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
export default function Boxes({ token }) { export default function Boxes({ token }) {
const [boxes, setBoxes] = useState([]); const [boxes, setBoxes] = useState([]);
const [newBoxName, setNewBoxName] = useState(''); const [newBoxName, setNewBoxName] = useState('');
const apiUrl = `${process.env.REACT_APP_API_URL}/boxes`;
const debugApi = () => {
if (process.env.DEBUG_API) {
console.log("URL is " + apiUrl);
}
};
debugApi();
useEffect(() => { useEffect(() => {
//console.log('Token:' + token); fetchBoxes();
axios.get(`${process.env.REACT_APP_API_URL}/api/v1/boxes`, {
headers: { Authorization: `Bearer ${token}` }
}).then(response => {
setBoxes(response.data);
});
}, [token]); }, [token]);
// Log boxes state changes outside the useEffect const fetchBoxes = async () => {
useEffect(() => { try {
//console.log('Boxes updated:', boxes); const response = await api.boxes.getAll(token);
}, [boxes]); setBoxes(response.data);
} catch (error) {
const handleCreateBox = () => { console.error('Error fetching boxes:', error);
axios.post(`${process.env.REACT_APP_API_URL}/api/v1/boxes`, { name: newBoxName }, { }
headers: { Authorization: `Bearer ${token}` }
}).then(response => {
setBoxes([...boxes, response.data]);
setNewBoxName('');
});
}; };
const handleDeleteBox = (id) => { const handleCreateBox = async () => {
axios.delete(`${process.env.REACT_APP_API_URL}/api/v1/boxes/${id}`, { try {
headers: { Authorization: `Bearer ${token}` } const response = await api.boxes.create(token, { name: newBoxName });
}).then(() => { setBoxes([...boxes, response.data]);
setNewBoxName('');
} catch (error) {
console.error('Error creating box:', error);
}
};
const handleDeleteBox = async (id) => {
try {
await api.boxes.delete(token, id);
setBoxes(boxes.filter(box => box.ID !== id)); setBoxes(boxes.filter(box => box.ID !== id));
}); } catch (error) {
console.error('Error deleting box:', error);
}
}; };
return ( return (

View File

@ -1,33 +1,24 @@
// src/components/ItemDetails.js // src/components/ItemDetails.js
import React, { useState, useEffect, useRef, useCallback } from 'react'; import React, { useState, useEffect, useRef, useCallback } from 'react';
import { TextField, Button, Container, Avatar, Tooltip } from '@mui/material'; import { TextField, Button, Container, Avatar, Tooltip } from '@mui/material';
import axios from 'axios';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
//import { useNavigate } from 'react-router-dom'; // Import useNavigate import { api } from '../services/api';
export default function ItemDetails({ item, token, onSave, onClose, boxId }) { export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
const [name, setName] = useState(item.name); const [name, setName] = useState(item.name);
const [description, setDescription] = useState(item.description); const [description, setDescription] = useState(item.description);
const [imagePath, setImagePath] = useState(item.image_path || ''); const [imagePath, setImagePath] = useState(item.image_path || '');
const [imageSrc, setImageSrc] = useState('/images/default.jpg'); // Initial default image const [imageSrc, setImageSrc] = useState('/images/default.jpg');
const fileInputRef = useRef(null); // Add this line to define fileInputRef const fileInputRef = useRef(null);
const [imageOverlayVisible, setImageOverlayVisible] = useState(false); const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
// const navigate = useNavigate(); // Initialize useNavigate
// eslint says boxName is defined but never used, but when I remove it it fails to compile
// because boxName is undefined
// eslint-disable-next-line
const [boxName, setBoxName] = useState(''); const [boxName, setBoxName] = useState('');
const [boxes, setBoxes] = useState([]); const [boxes, setBoxes] = useState([]);
const [selectedBoxId, setSelectedBoxId] = useState(item.box_id); const [selectedBoxId, setSelectedBoxId] = useState(item.box_id);
//console.log("item.box_id: " + item.box_id);
useEffect(() => { useEffect(() => {
const fetchBoxes = async () => { const fetchBoxes = async () => {
try { try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/boxes`, { const response = await api.boxes.getAll(token);
headers: { Authorization: `Bearer ${token}` }
});
setBoxes(response.data); setBoxes(response.data);
} catch (error) { } catch (error) {
console.error('Error fetching boxes:', error); console.error('Error fetching boxes:', error);
@ -36,15 +27,12 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
fetchBoxes(); fetchBoxes();
}, [token]); }, [token]);
const handleBoxChange = (event) => { const handleBoxChange = (event) => {
const newBoxId = event.target.value; const newBoxId = event.target.value;
setSelectedBoxId(newBoxId); // Update only this state setSelectedBoxId(newBoxId);
//console.log('Selected box ID:', newBoxId);
}; };
useEffect(() => { useEffect(() => {
// Fetch box details only when the selectedBoxId changes
const getBoxDetails = async (boxId) => { const getBoxDetails = async (boxId) => {
try { try {
const boxIdNumber = +boxId; const boxIdNumber = +boxId;
@ -52,134 +40,71 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
console.error('Invalid boxId:', boxId); console.error('Invalid boxId:', boxId);
return; return;
} }
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxIdNumber}`, { const response = await api.boxes.getAll(token);
headers: { Authorization: `Bearer ${token}` } const box = response.data.find(b => b.ID === boxIdNumber);
}); if (box) {
setBoxName(response.data.name); setBoxName(box.name);
}
} catch (error) { } catch (error) {
console.error('Error fetching box details:', error); console.error('Error fetching box details:', error);
} }
}; };
if (selectedBoxId !== item.box_id) { if (selectedBoxId !== item.box_id) {
getBoxDetails(selectedBoxId); // Fetch when selected box changes getBoxDetails(selectedBoxId);
//console.log("selectedBoxId:", selectedBoxId);
} else if (item.box_id) { } else if (item.box_id) {
getBoxDetails(item.box_id); // Fetch when boxId exists and selectedBoxId is empty getBoxDetails(item.box_id);
//console.log("item.box_id:", item.box_id);
} }
}, [selectedBoxId, token, item.box_id]); // Removed `boxId` from dependencies }, [selectedBoxId, token, item.box_id]);
useEffect(() => { useEffect(() => {
// Function to fetch image similar to getImageSrc in Items.js const fetchItemImage = async () => {
const getImageSrc = (itemId) => { try {
return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}/image`, { const response = await api.items.getImage(token, item.ID);
headers: { Authorization: `Bearer ${token}` }, const reader = new FileReader();
responseType: 'blob' reader.onload = () => setImageSrc(reader.result);
}) reader.readAsDataURL(response.data);
.then(response => { } catch (error) {
if (response.status === 200) { setImageSrc('/default.jpg');
return new Promise((resolve, reject) => { }
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(response.data);
});
} else {
throw new Error('Image fetch failed');
}
})
.catch(() => {
// Return the data URL of the default image if image fetch fails
return new Promise((resolve, reject) => {
const img = new Image();
img.src = '/default.jpg';
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
resolve(dataURL);
};
img.onerror = reject;
});
});
}; };
fetchItemImage();
// Fetch the image when the component mounts or the item changes
getImageSrc(item.ID).then(dataUrl => setImageSrc(dataUrl));
}, [item.ID, token]); }, [item.ID, token]);
// const handleCloseItemDetails = () => {
// onClose(); // Call the onClose prop to close the modal
// navigate(`/boxes/${boxId}/items`); // Navigate back to the items list
// };
const handleImageUpload = useCallback(async () => { const handleImageUpload = useCallback(async () => {
if (!fileInputRef.current.files[0]) return;
const formData = new FormData(); const formData = new FormData();
formData.append('image', fileInputRef.current.files[0]); formData.append('image', fileInputRef.current.files[0]);
try { try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/items/${item.ID}/upload`, formData, { const response = await api.items.uploadImage(token, item.ID, formData);
headers: { return response.data.imagePath;
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
});
// Handle successful upload (e.g., show a success message)
//console.log('Image uploaded successfully!', response.data.imagePath);
return response.data.imagePath; // Indicate successful upload
} catch (error) { } catch (error) {
// Handle upload error (e.g., show an error message)
console.error('Image upload failed:', error); console.error('Image upload failed:', error);
} }
}, [item.ID, token]); }, [item.ID, token]);
// eslint-disable-next-line const handleSave = useCallback(async () => {
const updateItemBoxId = async () => {
try {
// eslint-disable-next-line
const response = await axios.put(`${process.env.REACT_APP_API_URL}/api/v1/items/${item.id}`, {
box_id: selectedBoxId,
}, {
headers: { Authorization: `Bearer ${token}` }
});
// Update the item's boxId
item.box_id = selectedBoxId;
} catch (error) {
console.error('Error updating item boxId:', error);
}
};
const handleSave = useCallback( async () => {
let imagePath; let imagePath;
// 1. Handle image upload first if a new image is selected
if (fileInputRef.current.files[0]) { if (fileInputRef.current.files[0]) {
// eslint-disable-next-line
imagePath = await handleImageUpload(); imagePath = await handleImageUpload();
} }
//console.log("Selected box ID:", selectedBoxId)
// 2. Update item details (name, description, etc.)
try { try {
await axios.put(`${process.env.REACT_APP_API_URL}/api/v1/items/${item.ID}`, { await api.items.update(token, item.ID, {
name, name,
description, description,
box_id: +selectedBoxId, // Ensure the updated selected box is saved box_id: +selectedBoxId,
}, {
headers: { Authorization: `Bearer ${token}` }
}); });
onSave(); // Notify parent to refresh items onSave();
} catch (error) { } catch (error) {
// Handle update error
console.error('Item update failed:', error); console.error('Item update failed:', error);
} }
}, [item.ID, name, description, selectedBoxId, token, onSave, handleImageUpload]); }, [item.ID, name, description, selectedBoxId, token, onSave, handleImageUpload]);
const handleImageError = (e) => { const handleImageError = (e) => {
e.target.src = '/images/default.jpg'; // Fallback to default image on error e.target.src = '/images/default.jpg';
}; };
const handleAvatarClick = () => { const handleAvatarClick = () => {
@ -194,13 +119,12 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
<Container> <Container>
<h3>Edit Item: {item.name}</h3> <h3>Edit Item: {item.name}</h3>
{/* Display the item image as an avatar */}
<Tooltip title="Click to enlarge"> <Tooltip title="Click to enlarge">
<Avatar <Avatar
src={imageSrc} src={imageSrc}
alt={name} alt={name}
onError={handleImageError} onError={handleImageError}
sx={{ width: 200, height: 200, marginBottom: '16px' }} // Style the Avatar sx={{ width: 200, height: 200, marginBottom: '16px' }}
onClick={handleAvatarClick} onClick={handleAvatarClick}
/> />
</Tooltip> </Tooltip>
@ -242,14 +166,11 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
accept="image/*" accept="image/*"
ref={fileInputRef} ref={fileInputRef}
style={{ display: 'none' }} style={{ display: 'none' }}
id="editItemImageUpload" // Unique ID id="editItemImageUpload"
/> />
<select value={selectedBoxId} onChange={handleBoxChange}> <select value={selectedBoxId} onChange={handleBoxChange}>
<option value="">No box</option> <option value="">No box</option>
{boxes.map((box) => ( {boxes.map((box) => (
// eslint-disable-next-line
//console.log('Box at the selection point:', box.ID),
//console.log("Box name:", box.name),
<option key={box.ID} value={box.ID}> <option key={box.ID} value={box.ID}>
{box.name} {box.name}
</option> </option>
@ -265,7 +186,6 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
id="image-upload" id="image-upload"
style={{ display: 'none' }} style={{ display: 'none' }}
onChange={(e) => { onChange={(e) => {
// You can handle image preview here if needed
setImagePath(e.target.files[0].name); setImagePath(e.target.files[0].name);
}} }}
/> />

View File

@ -29,6 +29,7 @@ import axios from 'axios';
import { useParams, useLocation } from 'react-router-dom'; import { useParams, useLocation } from 'react-router-dom';
import ItemDetails from './ItemDetails'; import ItemDetails from './ItemDetails';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
export default function Items({ token }) { export default function Items({ token }) {
const { id: boxId } = useParams(); const { id: boxId } = useParams();
@ -131,62 +132,30 @@ export default function Items({ token }) {
* *
* @return {Promise<void>} * @return {Promise<void>}
*/ */
const handleSaveNewItem = async () => { const handleSaveNewItem = async () => {
try { try {
// Step 1: Create the item first const newItemResponse = await api.items.create(token, {
// This sends a request to the API to create a new item with the
// name and description provided. The box_id is set to the selected
// box ID.
const newItemResponse = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/items`, {
name: newItemName, name: newItemName,
description: newItemDescription, description: newItemDescription,
box_id: parseInt(boxId, 10) // Ensure boxId is converted to an integer box_id: parseInt(boxId, 10)
}, {
headers: {
Authorization: `Bearer ${token}`
}
}); });
console.log('New item created:', newItemResponse.status);
// Step 2: If item creation is successful, upload the image
if (newItemResponse.status === 200 && fileInputRef.current.files[0]) { if (newItemResponse.status === 200 && fileInputRef.current.files[0]) {
// Get the ID of the newly created item const newItemId = newItemResponse.data.id;
const newItemId = newItemResponse.data.id;
// Get the image file that was uploaded
const imageFile = fileInputRef.current.files[0]; const imageFile = fileInputRef.current.files[0];
// Generate a unique image name by appending a random string
// to the image file name. This is used to prevent overwriting
// of images with the same name.
const newImageName = generateUniqueImageName(imageFile.name); const newImageName = generateUniqueImageName(imageFile.name);
const formData = new FormData();
// Upload the image file with the unique name to the server formData.append('image', new File([imageFile], newImageName, {
const uploadedImagePath = await handleImageUpload(newItemId, fileInputRef.current.files[0], newImageName); type: imageFile.type,
}));
if (uploadedImagePath) {
// The image was uploaded successfully. Log the uploaded image path await api.items.uploadImage(token, newItemId, formData);
console.log("Image path to save:", uploadedImagePath);
// You might want to update your item in the backend with the image path
// For example:
// await axios.put(...);
} else {
// The image upload failed. Log an error message
console.error('Failed to upload image for the new item.');
}
} }
// Close the add item dialog handleCloseAddItemDialog();
handleCloseAddItemDialog(); fetchItems();
// Fetch the items again to get the latest data
fetchItems();
} catch (error) { } catch (error) {
// Catch any errors that may occur during the item creation
// and image upload process. Log the error message
console.error('Error adding item:', error); console.error('Error adding item:', error);
} }
}; };
@ -252,22 +221,29 @@ export default function Items({ token }) {
}, [token]); }, [token]);
const fetchItems = useCallback(() => { const fetchItems = useCallback(() => {
axios.get( url, { const fetchData = boxId ?
headers: { Authorization: `Bearer ${token}` } api.items.getByBox(token, boxId) :
}).then(response => { api.items.getAll(token);
fetchData
.then(response => {
setItems(response.data); setItems(response.data);
// Fetch images for each item // Fetch images for each item
response.data.forEach(item => { response.data.forEach(item => {
getImageSrc(item.ID).then(imageDataUrl => { api.items.getImage(token, item.ID)
setItemImages(prevItemImages => ({ .then(response => {
...prevItemImages, const reader = new FileReader();
[item.ID]: imageDataUrl reader.onload = () => {
})); setItemImages(prev => ({
}); ...prev,
[item.ID]: reader.result
}));
};
reader.readAsDataURL(response.data);
});
}); });
}); });
}, [token, getImageSrc, url]); }, [token, boxId]);
// lint says I don't need boxId here // lint says I don't need boxId here
useEffect(() => { useEffect(() => {
@ -302,11 +278,10 @@ export default function Items({ token }) {
// }; // };
const handleDeleteItem = (itemId) => { const handleDeleteItem = (itemId) => {
axios.delete(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}`, { api.items.delete(token, itemId)
headers: { Authorization: `Bearer ${token}` } .then(() => {
}).then(() => { fetchItems();
fetchItems(); });
});
}; };
const handleEditItem = (item) => { const handleEditItem = (item) => {

View File

@ -1,27 +1,27 @@
// src/components/Login.js // src/components/Login.js
import React, { useState } from 'react'; import React, { useState } from 'react';
import { Button, TextField, Container, Typography, Alert } from '@mui/material'; import { Button, TextField, Container, Typography, Alert } from '@mui/material';
import axios from 'axios';
import { useNavigate } from 'react-router-dom'; // Import useNavigate import { useNavigate } from 'react-router-dom'; // Import useNavigate
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App'; import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
export default function Login({ setToken }) { export default function Login({ setToken }) {
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [loginError, setLoginError] = useState(false); // State for login error const [loginError, setLoginError] = useState(false);
const navigate = useNavigate(); // Initialize useNavigate const navigate = useNavigate();
const handleLogin = async (e) => { const handleLogin = async (e) => {
e.preventDefault(); e.preventDefault();
setLoginError(false); // Reset error state on each login attempt setLoginError(false);
try { try {
// eslint-disable-next-line no-template-curly-in-string const response = await api.login({ username, password });
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/login`, { username, password }); setToken(response.data.token);
setToken(response.data.token); navigate('/boxes');
navigate('/boxes');
} catch (error) { } catch (error) {
console.error('Login failed', error); console.error('Login failed', error);
setLoginError(true); // Set error state if login fails setLoginError(true);
} }
}; };

72
src/services/api.js Normal file
View File

@ -0,0 +1,72 @@
// src/services/api.js
import axios from 'axios';
const createApiClient = () => {
const client = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
const authHeader = (token) => ({ Authorization: `Bearer ${token}` });
return {
// Auth
login: (credentials) =>
client.post('/api/v1/login', credentials),
// Items
items: {
getAll: (token) =>
client.get('/api/v1/items', { headers: authHeader(token) }),
getOne: (token, id) =>
client.get(`/api/v1/items/${id}`, { headers: authHeader(token) }),
create: (token, itemData) =>
client.post('/api/v1/items', itemData, { headers: authHeader(token) }),
update: (token, id, itemData) =>
client.put(`/api/v1/items/${id}`, itemData, { headers: authHeader(token) }),
delete: (token, id) =>
client.delete(`/api/v1/items/${id}`, { headers: authHeader(token) }),
uploadImage: (token, id, formData) =>
client.post(`/api/v1/items/${id}/upload`, formData, {
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
}),
getImage: (token, id) =>
client.get(`/api/v1/items/${id}/image`, {
headers: authHeader(token),
responseType: 'blob'
}),
getByBox: (token, boxId) =>
client.get(`/api/v1/boxes/${boxId}/items`, { headers: authHeader(token) }),
},
// Boxes
boxes: {
getAll: (token) =>
client.get('/api/v1/boxes', { headers: authHeader(token) }),
create: (token, boxData) =>
client.post('/api/v1/boxes', boxData, { headers: authHeader(token) }),
delete: (token, id) =>
client.delete(`/api/v1/boxes/${id}`, { headers: authHeader(token) }),
},
// Admin
admin: {
getUsers: (token) =>
client.get('/api/v1/admin/user', { headers: authHeader(token) }),
createUser: (token, userData) =>
client.post('/api/v1/admin/user', userData, { headers: authHeader(token) }),
deleteUser: (token, id) =>
client.delete(`/api/v1/admin/user/${id}`, { headers: authHeader(token) }),
backupDb: (token) =>
client.get('/api/v1/admin/db', {
headers: authHeader(token),
responseType: 'blob'
}),
restoreDb: (token, formData) =>
client.post('/api/v1/admin/db', formData, {
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
}),
}
};
};
export const api = createApiClient();