import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
import { vtTokenSessionAuth } from "https://esm.town/v/stevekrouse/vtTokenSessionAuthSafe";
function App() {
const [tables, setTables] = useState([]);
const [selectedTable, setSelectedTable] = useState(null);
const [tableData, setTableData] = useState([]);
const [tableSchema, setTableSchema] = useState([]);
const [error, setError] = useState(null);
const [editingRow, setEditingRow] = useState(null);
const [newRow, setNewRow] = useState({});
useEffect(() => {
fetchTables();
}, []);
const fetchTables = async () => {
try {
const response = await fetch("/tables");
const data = await response.json();
setTables(data);
} catch (err) {
setError("Failed to fetch tables");
}
};
const fetchTableData = async (tableName) => {
try {
const dataResponse = await fetch(`/table/${tableName}`);
const data = await dataResponse.json();
setTableData(data);
const schemaResponse = await fetch(`/schema/${tableName}`);
const schema = await schemaResponse.json();
setTableSchema(schema);
setSelectedTable(tableName);
const emptyRow = schema.reduce((acc, col) => {
acc[col.name] = "";
return acc;
}, {});
setNewRow(emptyRow);
} catch (err) {
setError(`Failed to fetch data for table ${tableName}`);
}
};
const handleEdit = (index) => {
setEditingRow(index);
};
const handleSave = async (index) => {
try {
const response = await fetch(`/update/${selectedTable}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(tableData[index]),
});
if (!response.ok) {
throw new Error("Failed to update row");
}
setEditingRow(null);
await fetchTableData(selectedTable);
} catch (err) {
setError(`Failed to update row: ${err.message}`);
}
};
const handleInputChange = (index, key, value) => {
const newData = [...tableData];
newData[index][key] = value;
setTableData(newData);
};
const handleNewRowInputChange = (key, value) => {
setNewRow(prev => ({ ...prev, [key]: value }));
};
const handleAddRow = async () => {
try {
const response = await fetch(`/insert/${selectedTable}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newRow),
});
if (!response.ok) {
throw new Error("Failed to add new row");