nyipyatki/frontend/src/utils/fetchHosting.tsx
2025-10-30 00:06:28 +02:00

80 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useState, useEffect } from 'react';
import type { Hosting } from '../types';
const mockData: Hosting = {
1: {
reservedBy: "",
name: "Матрац 160см",
capacity: 2
},
2: {
reservedBy: "Vasya",
name: "Кровать 120см",
capacity: 2
},
3: {
reservedBy: "",
name: "Матрац 90см",
capacity: 1
},
4: {
reservedBy: "",
name: "Диван",
capacity: 1
},
};
const useFetchHosting = () => {
const [data, setData] = useState(mockData);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('/hosting');
if (response.status != 200) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
} finally {
setLoading(false);
}
};
const updateData = async (name: string, id: number) => {
setLoading(true);
setError(null);
try {
const response = await fetch(`/hosting/${id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ reservedBy: name })
});
if (!response.ok) { // Check for non-200 responses
const errorText = await response.text(); // Capture the response text for further insights
throw new Error(`Error ${response.status}: ${errorText}`);
}
// Optional: Fetch the updated data after reservation
await fetchData();
} finally {
setLoading(false);
}
};
useEffect(() => {
//fetchData(); // Initial fetch on mount
}, []);
return { data, error, loading, refetch: fetchData, update: updateData };
};
export default useFetchHosting;